1、ServletFileUpload
表单提交中当提交数据类型是multipare/form-data类型的时候,如果我们用servlet去做处理的话,该http请求就会被servlet容器,包装成httpservletRequest对象
,在由相应的servlet进行处理。
package com.jws.app.operater.service.impl; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import net.sf.json.JSONObject; import com.jws.app.operater.data.UserInfoMapper; import com.jws.app.operater.model.UserInfo; import com.jws.app.operater.service.PersionPhoteAuthServer; import com.jws.common.constant.Constants; import com.jws.common.constant.ConstantsCode; import com.jws.common.util.JiveGlobe; import com.jws.common.util.ResultPackaging; @Service"persionPhoteAuthServerImpl") public class PersionPhoteAuthServerImpl implements PersionPhoteAuthServer { @Resource private UserInfoMapper userInfoMapper; private final Logger logger = Logger.getLoggerthis.getClass)); @Override public JSONObject uploadPhotoHttpServletRequest reques) { JSONObject returnObject = new JSONObject); String path = Constants.imageUrl; File repositoryFile = new Filepath); if !repositoryFile.exists)) {repositoryFile.mkdirs);} FileItemFactory factory = new DiskFileItemFactory1024 * 32,repositoryFile); ServletFileUpload upload = new ServletFileUploadfactory); upload.setHeaderEncoding"utf-8"); upload.setSizeMax1024 * 1024 * 500); List<?> fileItr = null; try { fileItr = upload.parseRequestreques); // 讲非文件值放在map中 HashMap<String, String> map = new HashMap<>); Iterator<?> iter = fileItr.iterator); while iter.hasNext)) { FileItem item = FileItem) iter.next); if item.isFormField)) { map.putitem.getFieldName), item.getString)); } } // 验证参数 if map == null || !map.containsKey"openid")) { returnObject =ResultPackaging.dealJsonObjectConstantsCode.RESULT_CODE_FAIL, ConstantsCode.CODE_LACK_PARAMETER, null); return returnObject; } String openid = map.get"openid"); //处理文件 boolean isTrue = true; String filename = ""; Iterator<?> iter1 = fileItr.iterator); while iter1.hasNext)) { FileItem f = FileItem) iter1.next); if !f.isFormField)) { //详情 name=abc.png, size=376507 bytes, isFormField=false, FieldName=picture1 filename = f.getName) == null ? "" : f.getName); filename = JiveGlobe.getFromRom)+".jpg"; File saveFile = new Filepath, filename); if saveFile.exists)) { isTrue = false;break;} f.writesaveFile); } } ifJiveGlobe.isEmptyfilename)){ returnObject =ResultPackaging.dealJsonObjectConstantsCode.RESULT_CODE_FAIL, ConstantsCode.CODE_LACK_PARAMETER, null); return returnObject; } returnObject =ResultPackaging.dealJsonObjectConstantsCode.RESULT_CODE_SUCCESS, ConstantsCode.RESULT_CODE_SUCCESS, null); //保存文件信息 UserInfo rd = new UserInfo); rd.setSpareField1"1"); rd.setSpareField3filename); rd.setOpenIdopenid); userInfoMapper.updateByPrimaryKeyrd); } catch Exception e) { System.out.printlne); logger.error"###认证失败"+e); } return returnObject; } }
View Code
2、MultipartFile
@RequestMapping"/upload") @ResponseBody public String handleFileUpload@RequestParam"file") MultipartFile file) { if file.isEmpty)) { return "文件为空"; } // 获取文件名 String fileName = file.getOriginalFilename); System.out.println"上传的文件名为:" + fileName); // 获取文件的后缀名 String suffixName = fileName.substringfileName.lastIndexOf".")); System.out.println"上传的后缀名为:" + suffixName); // 文件上传后的路径 String filePath = "D://"; File dest = new FilefilePath + fileName); // 检测是否存在目录 if !dest.getParentFile).exists)) { dest.getParentFile).mkdirs); } try { file.transferTodest); return "上传成功"; } catch IllegalStateException e) { e.printStackTrace); } catch IOException e) { e.printStackTrace); } return "上传失败"; }
View Code
/** * 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile * * @param request * @return */ @RequestMappingvalue = "/batch/upload", method = RequestMethod.POST) public @ResponseBody String handleFileUpload1HttpServletRequest request) { List<MultipartFile> files = MultipartHttpServletRequest) request).getFiles"file"); String filePath = "D://"; MultipartFile file = null; for int i = 0; i < files.size); ++i) { file = files.geti); // 获取文件名 String fileName = file.getOriginalFilename); System.out.println"上传的文件名为:" + fileName); if !file.isEmpty)) { File dest = new FilefilePath + fileName); // 检测是否存在目录 if !dest.getParentFile).exists)) { dest.getParentFile).mkdirs); } try { file.transferTodest); } catch Exception e) { return "上传失败 " + i + " => " + e.getMessage); } } else { return "上传失败 " + i + " 文件为空."; } } return "上传成功"; }
View Code
3、CommonsMultipartResolver
*
* @param request
* @return
*/
@ResponseBody
@RequestMapping“/uploadFile”)
public Map<String, Object> uploadFileHttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>);
// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolverrequest.getSession).getServletContext));
// 检查form中是否有enctype=”multipart/form-data”
if multipartResolver.isMultipartrequest)) {
// 将request变成多部分request
MultipartHttpServletRequest multiRequest = MultipartHttpServletRequest) request;
// 获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames);
while iter.hasNext)) {
// 一次遍历所有文件
MultipartFile file = multiRequest.getFileiter.next).toString));
try {
if file != null && StringUtils.isNotBlankfile.getOriginalFilename).trim))) {
Map<String, String> metas = new HashMap<String, String>);
// 取得文件后缀
String filename = file.getOriginalFilename);
String newFileName = System.currentTimeMillis) + int) Math.random) * 100)
+ filename.substringfilename.lastIndexOf“.”));
metas.putStorageConstants.META_KEY_FILENAME, newFileName);
String imgUrl = storageService.storefile.getBytes), metas);
map.put“imgUrl”, imgUrl);
map.put“retCode”, “success”);
// map.put“imgUrl”,
// “https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=611483611,2895064642&fm=117&gp=0.jpg”);
}
} catch Exception e) {
e.printStackTrace);
}
}
} else {
map.put“retCode”, “error”);
}
return map;
转载于:https://www.cnblogs.com/kimobolo/p/7109999.html