<form action="${pageContext.request.contextPath }/Upload" method="post" enctype="multipart/form-data">
请选择上传的文件1:<input type="file" name="attachment1"/>
请选择上传的文件2:<input type="file" name="attachment2"/>
<input type="submit" value="上传"/>
</form>
核心的API
DiskFileItemFactory factory = new DiskFileItemFactory(10*1024,new File("e:/temp/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8"); 设置文件名的编码
List<FileItem> list = upload.parseRequest(request);
FileItem file = list.get(0);
String fileName = file.getName();
long fileSize = file.getSize();
String contentType = file.getContentType();
InputStream in = file.getInputStream()
FileUtils.copyInputStreamToFile(in, new File("e:/files/"+fileName))
文件类型
String contentType = item.getContentType();
if(!contentType.contains("image/")){
throw new FileTypeErrorException("文件类型错误,请换一张!!");
}
文件大小
setFileSizeMax 设置限制单个文件的大小
FileSizeLimitExceededException e
setSizeMax: 设置一个请求中所有文件的总大小
SizeLimitExceededException e
文件的上传进度:
ServletFileUpload类:
upload.setProgressListener(new MyProgressListener() ): 设置文件上传的监听器
class MyProgressListener implements ProgressListener{
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("已经上传了"+pBytesRead+"字节,总字节数为"+pContentLength+"字节,现在正在上传第"+pItems+"个文件!");
}
获取非file普通表单组件的数据:
if(item.isFormField()){
//除file组件外的其他表单组件(text/password/select/hidden。。。。。)
if(item.getFieldName().equals("info1")){
String info1 = item.getString("utf-8");
System.out.println(info1);
} }
/**
* 对中文的文件名加入URLEncoder加密
* 请求发送数据: request 带中文 -> 浏览器传输(URLEncoder) -》( 服务器获取(URLDecoder))
响应发送数据: response 带中文( URLEncoder ) -> 浏览器传输 - 》 浏览器获取(URLDecoder)
*/
fileName = URLEncoder.encode(fileName, "utf-8");
response.setHeader("content-disposition", "attachment;filename="+fileName);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while( (len=in.read(buf))!=-1 ){
out.write(buf, 0, len);
}
out.close();
in.close();