美文网首页
springboot文件上传

springboot文件上传

作者: 李征兵 | 来源:发表于2019-07-17 14:36 被阅读0次

    文件大小限制

    springboot2.0以后都可以通过在application.yml中配置spring的属性来实现对上传文件大小的限制,一般有下列几个方式:

    1. 设置文件大小和请求大小,单位是Byte
    spring:
     servlet:
      multipart:
       maxFileSize: 300000
       maxRequestSize: 300000
    
    1. 如果不限制大小,则相关参数都为-1
    spring:
     servlet:
      multipart:
       maxFileSize: -1
       maxRequestSize: -1
    

    服务端实现

    使用spring注解@RequestPart(value = "file") MultipartFile file来接收来自客户端的文件数据,然后通过数据流处理该文件,例如:将文件以流的方式存储到MongoDB的GridFS中。

        @PostMapping(value = "/upload")
        public String save(@RequestPart(value = "file") MultipartFile file) {
            LOGGER.info("Saving file..");
            DBObject metaData = new BasicDBObject();
            metaData.put("createdDate", new Date());
    
            String fileName = UUID.randomUUID().toString();
            try {
                InputStream inputStream = file.getInputStream();
                gridFsTemplate.store(inputStream, fileName, file.getContentType(), metaData);
                LOGGER.info("文件存储:{}",fileName);
                inputStream.close();
            } catch (IOException e) {
                LOGGER.error("IOException: " + e);
            }
            return fileName;
        }
    

    还可以有一种更优的文件存储或者通过参数传递到其他服务的方式,就是将文件转换为base64。

    Base64.getEncoder().encodeToString(IOUtils.toByteArray(inputStream));
    

    相关文章

      网友评论

          本文标题:springboot文件上传

          本文链接:https://www.haomeiwen.com/subject/iapqlctx.html