Springboot实现文件上传下载

Springboot实现文件上传下载

前言

意图使用Springboot开发完成文件上传下载服务,将其以docker容器形式部署至服务器。

文件上传

首先,在项目工程目录结构上,构建Controller层、Service层。

1、代码片段
Controller层:

     /*
     * 实现文件上传
     */
    @Controller
    @RequestMapping(value = "/upload")
    @ResponseBody 
    @Slf4j
public class FileUploadController {
    @Autowired
    private FileUploadService fileUploadService;  
    @RequestMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam("fileName") MultipartFile file){
    String result = fileUploadService.fileUpload(file);
    return result;
    }   
}

Service层:

    @Service
    @Slf4j
public class FileUploadService {
    public String fileUpload(MultipartFile file){
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        String path = "./upload";
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try (FileOutputStream out = new FileOutputStream (dest)){
            out.write(file.getBytes());
                        
        } catch (Exception e) {          
            log.error("文件上传失败 :"+ e);
            return "false";
        }
    }
}

Note: file.transferTo( ); 此方法是Spring自带文件保存方法,其封装了write(),若路径是绝对路径,则使用没有问题;否则,会出现文件路径找不到错误。[查找相关资料显示,与spring-boot -starter-parent版本有关]

2、关于上传文件大小:
Springboot默认支持上传文件2M,超过2M文件,此处采用自定义maxFileSize、maxRequestSize;
新建配置类,加上@Configuration文件进行说明。
然后在类里面加上

@Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory(); 
        //单个文件最大
        factory.setMaxFileSize("10240KB"); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }

文件下载

1、代码片段
Controller层:

    @Controller
    @RequestMapping("/fileDownload")     
    public String downLoad(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String filename = request.getParameter("fileName");
        String filePath = "./download" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));//文件类型是按照文件的扩展名显示的,点保存后,文件以filename的值命名;适用于中文名出现情况
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {                
                log.error("文件下载错误:"+ e);
            }         
            finally {
                if(bis!=null){
                   try{
                       bis.close();
                   }catch(Exception e){
                       log.error("BufferedInputStream流关闭异常:"+ e);
                   }
                }
                if(fis!=null){
                    try{
                       fis.close();
                   }catch(Exception e){
                       log.error("FileInputStream流关闭异常:"+ e);
                   }                   
                }
                if(os!=null){
                   try{
                       os.close();
                   }catch(Exception e){
                       log.error("OutputStream流关闭异常:"+ e);
                   }                   
                }
            }        
        return null;
    }

Postman测试

http://localhost:8080/upload/fileUpload

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值