Jojo的作业系统

本文详细介绍了使用Spring Boot实现文件上传和下载的功能。通过代码示例,展示了如何处理MultipartFile对象进行文件上传,并确保文件路径的正确性。同时,讲解了如何通过HttpServletResponse进行文件下载,包括设置响应头以实现文件的正确下载。

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

简单的文件上传

代码如下

@RestController
@RequestMapping("/file")
public class FileController {
    @RequestMapping(method = RequestMethod.POST, value ="/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") MultipartFile file) throws IOException {
        System.out.println("file name = "+file.getOriginalFilename());
        if (file.isEmpty()) {
            return "file is empty";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上产的路径
        String filePath = "d:\\macro";
        // fileName处理
//        fileName = filePath+ UUID.randomUUID()+fileName;
        fileName = filePath+ Path.SEPARATOR+fileName;
        // 文件对象
        File dest = new File(fileName);
        // 创建路径
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

    }

    @RequestMapping("download")
    public void download(HttpServletResponse response) throws FileNotFoundException {
        File file =new File("C:\\Users\\ASUS\\Desktop\\spring-boot-reference.pdf");
        FileInputStream fileInputStream=new FileInputStream(file);
        // 设置被下载而不是被打开
        response.setContentType("application/gorce-download");
        // 设置被第三方工具打开,设置下载的文件名
        response.addHeader("Content-disposition","attachment;fileName=spring-boot-reference.pdf");
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Postman的设置,注意不要添加任何header
Postman的设置

引入注册登录系统

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值