标签:ann nbsp serve use NPU 应用程序 内容类型 sub mooc
import org.apache.commons.fileupload.FileItem; import java.util.HashMap; import java.util.Map; public class ParamDto { private Map<String,String> paramMap; private Map<String,FileItem> fileMap; public ParamDto() { paramMap = new HashMap<>(); fileMap = new HashMap<>(); } public Map<String, String> getParamMap() { return paramMap; } public void setParamMap(Map<String, String> paramMap) { this.paramMap = paramMap; } public Map<String, FileItem> getFileMap() { return fileMap; } public void setFileMap(Map<String, FileItem> fileMap) { this.fileMap = fileMap; } }
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.imooc.dto.ParamDto; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.List; public class RequestUtil { /** * 从request流中解析参数与上传的文件 * @param request */ public static ParamDto parseParam(HttpServletRequest request) { ParamDto result = new ParamDto(); //创建一个FileItem工厂 通过DiskFileItemFactory对象创建文件上传核心组件 ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); try { //通过文件上传核心组件解析request请求,获取到所有的FileItem对象 List<FileItem> fileItemList = upload.parseRequest(request); //遍历表单的所有表单项(FileItem) 并对其进行相关操作 for(FileItem fileItem : fileItemList) { //判断这个表单项如果是一个普通的表单项 if(fileItem.isFormField()) { result.getParamMap().put(fileItem.getFieldName(),fileItem.getString("UTF-8")); //如果不是表单的普通文本域,就是 } else { result.getFileMap().put(fileItem.getFieldName(),fileItem); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } }
import org.apache.commons.fileupload.FileItem; import java.io.File; public class FileUtil { /** * 上传文件的保存路径 */ public static final String SAVE_PATH = "d:/upload/"; /** * 保存上传的文件 * @param fileItem * @param path * @return * @throws Exception */ public static String save(FileItem fileItem,String path) throws Exception { String fileName = System.currentTimeMillis() + "_" + fileItem.getName(); fileItem.write(new File(path + fileName)); return fileName; } }
好啦~ 有空我们再来看看原始的文件上传方式
Java使用Commons-FileUpload组件实现文件上传最佳方案
标签:ann nbsp serve use NPU 应用程序 内容类型 sub mooc
原文地址:https://www.cnblogs.com/jimisun/p/9419269.html