package net.add1s.util;
import cn.hutool.core.io.resource.WebAppResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
/**
* @author github.com@lalafaye
*/
public class UploadUtils {
/**
* 所有文本字段
*/
public static final String TEXT_FIELDS = "text_fields";
/**
* 所有文件字段
*/
public static final String FILE_FIELDS = "file_fields";
/**
* 上传大小限制(2M)
*/
private static long maxUploadSize = 2097152;
/**
* 文件保存目录路径
*/
private static String savePath = "";
/**
* 文件上传保存文件夹名
*/
private static String basePath = "upload";
public static boolean upload(HttpServletRequest request) {
List<FileItem> fileList = (List<FileItem>) getAllItems(request).get(FILE_FIELDS);
System.out.println(fileList.size());
if (fileList != null) {
for (FileItem file : fileList) {
saveFile(file);
}
}
return false;
}
/**
* 获取表单中的所有文本和文件字段
*
* @param request
* @return map
*/
public static Map getAllItems(HttpServletRequest request) {
// savePath = new WebAppResource("\\" + basePath).toString();
savePath = "D:\\IntelliJ_IDEA_2018_3_1\\IDEA_workspace\\Confession\\src\\main\\webapp\\upload";
// 存储表单字段和非表单字段
Map<String, Object> map = new HashMap<>(2);
// 第一步:判断request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 阀值(10M),超过这个值才会写到临时目录,否则在内存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(savePath + "\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上传限制
upload.setSizeMax(maxUploadSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 第3步:处理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域对象List
List<FileItem> fileFieldsList = new ArrayList<>();
// 表单字段Map
Map<String, String> textFieldsMap = new HashMap<>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 处理所有表单元素和文件域表单元素
if (item.isFormField()) { // 表单元素
String name = item.getFieldName();
String value = item.getString();
textFieldsMap.put(name, value);
} else { // 文件域表单元素
fileFieldsList.add(item);
}
}
map.put(FILE_FIELDS, fileFieldsList);
map.put(TEXT_FIELDS, textFieldsMap);
}
}
return map;
}
public static AjaxResult saveFile(FileItem item) {
System.out.println(savePath);
// 文件名
String fileName = item.getName();
// 后缀
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 检查文件大小
if (item.getSize() > maxUploadSize) {
// TODO
return AjaxResult.me().setSuccess(false).setMsg("文件太大,上传失败");
} else {
String newFileName = UUID.randomUUID().toString() + "." + fileExt;
try {
IOUtils.copy(item.getInputStream(), new FileOutputStream(new File(savePath, newFileName)));
} catch (Exception e) {
e.printStackTrace();
}
}
System.gc();
return AjaxResult.me();
}
}
package net.add1s.util;
/**
* Ajax请求响应对象的类
*
* @author github.com@lalafaye
*/
public class AjaxResult {
private boolean success = true;
private String msg = "Successful operation!";
/**
* 返回到前台对象
*/
private Object resultObj;
public boolean isSuccess() {
return success;
}
public AjaxResult setSuccess(boolean success) {
this.success = success;
return this;
}
public String getMsg() {
return msg;
}
public AjaxResult setMsg(String msg) {
this.msg = msg;
return this;
}
public Object getResultObj() {
return resultObj;
}
public AjaxResult setResultObj(Object resultObj) {
this.resultObj = resultObj;
return this;
}
/**
* AjaxResult.me() 成功
* AjaxResult.me().setMsg() 成功
* AjaxResult.me().setSuccess(false).setMsg("失败");
*
* @return
*/
public static AjaxResult me() {
return new AjaxResult();
}
}