Springboot2.7 文件上传和下载

本文介绍了在Java中处理文件上传和下载的方法,包括如何使用`MultipartFile`处理上传文件,以及通过`@GetMapping(/download)`处理文件下载请求,对比了`outputStream.write()`和`outputStream.print()`的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、文件上传

public R<String> uploadFile(MultipartFile files){
        LocalDate now = LocalDate.now();
        int month = now.getMonthValue();
        int year = now.getYear();
        int day = now.getDayOfMonth();
        String s = UUID.randomUUID().toString().replace("-","");
        String filename = s+files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
        String returnFilename = year+"-"+month+"-"+day+"-"+filename;
        String filePath = uploadDir+"\\"+year+"\\"+month+"\\"+"\\"+day+"\\"+filename;
        File file = new File(filePath);
        if (!file.exists()){
            file.mkdirs();
        }

        try {
            files.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(returnFilename);

    }

2、文件下载

outputStream.write()

outputStream.print()

都可以将后端的数据响应的前端,但是仔细对比是有区别的,需要根据实际使用进行区分。

@GetMapping("/download")
    public void downloadFile(String name, HttpServletResponse response) throws IOException {

        String[] filename = name.split("-");
        String filePath = uploadDir+"/"+filename[0]+"/"+filename[1]+"/"+filename[2]+"/"+filename[3];

        File file = new File(filePath);
        if (file.exists()){
            byte[] bytes = new byte[1024];
            int read = 0;
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            response.setContentType("image/jpg");
            try {
                while ((read = fis.read(bytes)) != -1){
                    outputStream.write(bytes,0,read);
                    outputStream.flush();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                outputStream.close();
                fis.close();
            }

        }else{
           
            response.setContentType("text/html;charset=utf-8");
      
            response.getWriter().write("<h1>文件不存在</h1>");
      
            response.setStatus(203);
        }


    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工作这么多年,学会了内卷

共同加油,继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值