java组件commons-fileupload实现文件上传
作者:壹龙 时间:2022-10-02 08:33:14
一、所需要的包:
1、commons-fileupload-1.2.1.jar:
下载地址
http://commons.apache.org/downloads/download_fileupload.cgi
2、commons-io-1.4.jar:
下载地址
http://commons.apache.org/downloads/download_io.cgi
二、注意事项:
form表单里面要加上enctype="multipart/form-data"
三、代码示例
1、jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>upload</title>
</head>
<body>
<form action="uploadServlet" method="post" enctype="multipart/form-data">
<table>
<caption>上传实例</caption>
<tr>
<td>姓名</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td>年龄</td>
<td>
<input type="text" name="age">
</td>
</tr>
<tr>
<td>照片</td>
<td>
<input type="file" name="image">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
</body>
</html>
2、UploadServlet代码
package servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
/**
* 上传servlet
* @author lisanlai
*
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// 设置字符编码为UTF-8, 这样支持汉字显示
response.setCharacterEncoding("UTF-8");
Writer o = response.getWriter();
/**
* 首先判断form的enctype是不是multipart/form-data
* 同时也判断了form的提交方式是不是post
* 方法:isMultipartContent(request)
*/
if(ServletFileUpload.isMultipartContent(request)){
request.setCharacterEncoding("utf-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置文件存放的临时文件夹,这个文件夹要真实存在
File fileDir = new File("../webapps/fileupload/tmp/");
if(fileDir.isDirectory() && fileDir.exists()==false){
fileDir.mkdir();
}
factory.setRepository(fileDir);
//设置最大占用的内存
factory.setSizeThreshold(1024000);
//创建ServletFileUpload对象
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("utf-8");
//设置单个文件最大值byte
sfu.setFileSizeMax(102400000);
//所有上传文件的总和最大值byte
sfu.setSizeMax(204800000);
List<FileItem> items = null;
try {
items = sfu.parseRequest(request);
}catch (SizeLimitExceededException e) {
System.out.println("文件大小超过了最大值");
} catch(FileUploadException e) {
e.printStackTrace();
}
//取得items的迭代器
Iterator<FileItem> iter = items==null?null:items.iterator();
//图片上传后存放的路径目录
File images = new File("D:/upload/images/");
if(images.exists()==false){
images.mkdirs();
}
//迭代items
while(iter!=null && iter.hasNext()){
FileItem item = (FileItem) iter.next();
//如果传过来的是普通的表单域
if(item.isFormField()){
System.out.print("普通的表单域:");
System.out.print(new String(item.getFieldName()) + " ");
System.out.println(new String(item.getString("UTF-8")));
}
//文件域
else if(!item.isFormField()){
System.out.println("源图片:" + item.getName());
String fileName = item.getName().substring(item.getName().lastIndexOf("\\"));
BufferedInputStream in = new BufferedInputStream(item.getInputStream());
//文件存储在D:/upload/images目录下,这个目录也得存在
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(images.getAbsolutePath()+ fileName)));
Streams.copy(in, out, true);
o.write("文件上传成功");
}
}
}else {
System.out.println("表单的enctype 类型错误");
}
}
}
3、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>UploadTest</display-name>
<welcome-file-list>
<welcome-file>upload.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
本文已被整理到了《Java上传操作技巧汇总》,欢迎大家学习阅读。
标签:java,commons,fileupload,文件上传
0
投稿
猜你喜欢
Android图表库HelloChart绘制多折线图
2021-06-18 05:34:45
Kotlin开发笔记之委托属性与区间(译)
2022-07-12 19:14:32
Android使用VideoView出现无法播放此视频问题的解决方法
2023-01-16 18:01:41
Android自定义控件实现折线图
2023-02-09 18:33:55
java利用Socket实现聊天室功能实例
2022-11-10 01:25:43
Java深入浅出数组的定义与使用下篇
2022-12-04 10:27:38
android串口开发入门之搭建ndk开发环境及第一个jni调用程序
2023-03-14 16:54:55
详解C#中三个关键字params,Ref,out
2021-09-25 18:54:02
Java实现多文件压缩加密并重命名压缩文件对象的方法
2021-07-02 15:44:31
使用Springboot 打jar包实现分离依赖lib和配置
2023-01-29 18:35:29
java文件操作输入输出结构详解
2023-07-30 21:48:30
java使用FileVisitor遍历文件和目录
2021-07-17 13:25:21
谈谈变量命名规范的重要性
2021-08-10 22:40:13
eclipse下配置Spring环境的方法步骤
2023-02-27 20:39:26
Android基础之Fragment与Activity交互详解
2021-12-25 16:02:11
Java class文件格式之属性_动力节点Java学院整理
2021-06-13 01:52:00
SpringBoot+SpringSession+Redis实现session共享及唯一登录示例
2023-10-07 07:56:17
Android自定义加载圈动画效果
2021-07-20 14:52:23
C#算法之散列表
2022-07-30 19:05:52
Logger.error打印错误异常的详细堆栈信息
2022-01-06 23:03:04