spring mvc文件上传
package com.haier.controller.newuser; import com.haier.commons.entity.Response; import com.haier.commons.utils.AliyunOSSUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.UUID; /** * 文件操作Controller. * * @author Will Tong * */ @Controller @RequestMapping("/file") public class FileController { private Logger log = Logger.getLogger(getClass()); private static long PICMAXSIZE = 2097152; private static long FILEMAXSIZE= 10485760;//定义文件上传的最大大小为5M @RequestMapping(value ="/uploadfile",produces="text/plain;charset=UTF-8") @ResponseBody public String uploadFile(HttpServletRequest request, @RequestParam(required = false) MultipartFile streamFile) { Response<String> response=new Response<>(); String fileName = streamFile.getOriginalFilename(); if (!StringUtils.isEmpty(fileName)) { try { if (streamFile.getSize() <= FILEMAXSIZE) { // String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$"; // Pattern pattern = Pattern.compile(reg); // Matcher matcher = pattern.matcher(streamFile.getOriginalFilename().toLowerCase()); UUID uuid = UUID.randomUUID(); String resultFileName = uuid.toString() + "." + this.getExtensionName(fileName); File file = new File(request.getSession().getServletContext().getRealPath("/") + "temp/", resultFileName); FileUtils.copyInputStreamToFile(streamFile.getInputStream(), file); String uri = AliyunOSSUtil.PutObject(AliyunOSSUtil.ClassificationEnum.MECV,AliyunOSSUtil.FolderEnum.ORDER , resultFileName, file); // 上传后删除 file.delete(); String url = "http://" + AliyunOSSUtil.GetBucket() + "." + AliyunOSSUtil.GetDomain() + "/" + uri; response.setResult(url); } else { response.setError("图片大小超过5M,请重新选择!"); } } catch (Exception e) { log.error(String.format("图片上传失败失败")); response.setError("图片上传失败失败!"); } }else{ response.setError("图片名字为空无法上传!"); } return response.toJson(); } public String getExtensionName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot >-1) && (dot < (filename.length() - 1))) { return filename.substring(dot + 1); } } return filename; } }