package com.mzl.flower.web.upload; import com.mzl.flower.base.BaseController; import com.mzl.flower.base.R; import com.mzl.flower.config.UploadProperties; import com.mzl.flower.config.exception.ValidationException; import com.mzl.flower.dto.response.upload.UploadResultDTO; import com.mzl.flower.utils.FileUtil; import com.mzl.flower.utils.UUIDGenerator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; @RestController @RequestMapping("/api/upload") @Api(value = "文件上传", tags = "文件上传") public class FileUploadResource extends BaseController { @Autowired private UploadProperties uploadProperties; private static List fileType = Arrays.asList("zip", "jpg", "png", "gif", "jpeg", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "mp4", "wmv", "rmvb", "mpg", "mpeg", "3gp", "mov", "m4v", "avi", "flv"); @PostMapping("/file") @ResponseBody @ApiOperation(value = "上传文件", httpMethod = "POST", notes = "上传文件") public ResponseEntity uploadFile(final String _fileName, HttpServletRequest request) throws Exception { List result = new ArrayList(); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; Iterator iter = mRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = mRequest.getFile(iter.next()); String fileName = null; if (StringUtils.isNotEmpty(_fileName)) { fileName = _fileName; } else { fileName = file.getOriginalFilename(); } //获取文件类型 String extName; try { extName = fileName.substring(fileName.lastIndexOf(".")) .toLowerCase(); extName = extName.replace(".", ""); } catch (Exception e) { extName = ""; } if (!fileType.contains(extName.toLowerCase())) { throw new ValidationException("文件类型格式不正确"); } byte[] bytes = file.getBytes(); String path = uploadProperties.getLocalServerPath(); UploadResultDTO uploadResult = new UploadResultDTO(); uploadResult.setName(fileName); fileName = UUIDGenerator.getUUID() + FileUtil.getFileEndfix(fileName); String url = FileUtil.saveFile(path, bytes, fileName, uploadProperties.getFileGroup()); uploadResult.setUrl(uploadProperties.getFileServerPath() + url); uploadResult.setType(extName); uploadResult.setSize(file.getSize()); result.add(uploadResult); } if (result.isEmpty()) { throw new ValidationException("文件为空"); } return returnData(R.SUCCESS.getCode(), result); } }