SpringBoot后台接收File文件

application.yml配置

spring:
  profiles.active: aeolian
## MULTIPART (MultipartProperties)
# 开启 multipart 上传功能
  servlet.multipart.enabled: true
# 文件写入磁盘的阈值
  servlet.multipart.file-size-threshold: 1KB
# 最大文件大小
  servlet.multipart.max-file-size: 200MB
# 最大请求大小
  servlet.multipart.max-request-size: 215MB

## 文件存储所需参数
# 所有通过 REST APIs 上传的文件都将存储在此目录下
file.upload-dir: ./uploads

Controller

@RestController
@RequestMapping("/wx/media")
public class MediaController {

    @Resource
    private WxCpProperties properties;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 临时文件上传 - 只有一个文件
     * @param type
     * @param request
     * @return
     * @throws WxErrorException
     * @throws IOException
     */
    @RequestMapping(value = "/uploadTemp/{type}", method = {RequestMethod.GET,RequestMethod.POST},produces = "application/json;charset=UTF-8")
    public String sendMessage(@PathVariable String type,HttpServletRequest request) throws WxErrorException, IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile multipartFile = null;
        if (files.size()>0){
            multipartFile = files.get(0);
        }else {  /*读取文件失败*/
            logger.error("临时文件上传失败,未读取到文件!");
            mediaResult.setErrmsg("未读取到上传的文件!请确保Content-Type为multipart/form-data;并且文件参数的key为file");
            return JsonUtils.toJson(mediaResult);
        }
        /*验证上传文件大小,防止浪费空间内存*/
        long sizeMb = multipartFile.getSize() / (1024 * 1024);
        if (sizeMb > 50){
            mediaResult.setErrmsg("文件过大,详情查看 https://work.weixin.qq.com/api/doc/90000/90135/90253");
            return JsonUtils.toJson(mediaResult);
        }
        String result = "";
        /*主要业务逻辑*/
        return result;
    }
}

 

上一篇:HTML5在路上


下一篇:axios 上传文件出现 the request was rejected because no multipart boundary was found