文件上傳與下載
1. 文件上傳
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
1.1 前臺頁面
<form action="/xx/controller" method="post" enctype="multipart/form-data">
<input type="file" name="headimg" value="${stu.headimg}">
<input type="submit" value="確定提交">
</form>
1.2 抽取工具類
- 需要注意的問題:同一個req對象只能被parseRequest(req)解析一次,如果進行第二次解析,req對象中攜帶的表單數據全部爲空。
public class FileUploadUtil {
static List<String> list = Arrays.asList("jpg","png","bmp");
public static Map<String,String[]> upload(HttpServletRequest req){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Map<String,String[]> map = new HashMap<>();
try {
upload.setFileSizeMax(1024*1024);
upload.setSizeMax(1024*1024*2);
List<FileItem> fileItems = upload.parseRequest(req);
Iterator<FileItem> iterator = fileItems.iterator();
while (iterator.hasNext()){
FileItem item = iterator.next();
if(item.isFormField()){
String fieldName = item.getFieldName();
String value = item.getString("UTF-8");
if(map.containsKey(fieldName)){
String[] oldvalue = map.get(fieldName);
String[] newvalue = new String[oldvalue.length+1];
System.arraycopy(oldvalue,0,newvalue,0,oldvalue.length);
newvalue[newvalue.length-1] = value;
map.put(fieldName,newvalue);
}
if(!map.containsKey(fieldName)){
map.put(fieldName,new String[]{value});
}
}else if(item.getSize()==0){
map.put("headimg",null);
}else{
String filename = item.getName();
String name = FilenameUtils.getName(filename);
String realPath = req.getServletContext().getRealPath("/img");
File dir = new File(realPath);
dir.mkdirs();
String uuid = UUIDUtil.getUUID();
String extension = FilenameUtils.getExtension(filename);
if(!list.contains(extension)){
throw new AutoException("不是指定的文件,請選擇jpg、png格式的文件!");
}
String path = req.getServletContext().getContextPath()+"/img/"+uuid+"-"+name;
map.put("headimg",new String[]{path});
File uploadFile = new File(dir,uuid+"-"+name);
item.write(uploadFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}