Spring Boot文档阅读笔记-FileHandling解析及抓包分析

140 篇文章 4 订阅
47 篇文章 1 订阅

这篇博文将说明使用WEB服务上传和下载文件。

首先是文件上传:

使用MultipartFile作为请求参数,这个上传API使用Multi-Part表单的值:

代码如下:

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String fileUpload(@RequestParam("file")MultipartFile file) throws IOException {

        File convertFile = new File("./" + file.getOriginalFilename());
        convertFile.createNewFile();
        FileOutputStream fout = new FileOutputStream(convertFile);
        fout.write(file.getBytes());
        fout.close();

        return "File is upload successfully";
    }

下面是文件下载:

使用InputStreamResource获取需要下载的文件,然后将http头设置为Content-Disposition,并且还需指定响应为流媒体。

完整代码如下:

    @GetMapping(value = "/download")
    public ResponseEntity<Object> download(@RequestParam("fileName") String fileName) throws FileNotFoundException {

        File file = new File(fileName);
        InputStreamResource inputStreamResource = new InputStreamResource(new FileInputStream(file));

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        httpHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");
        httpHeaders.add("Pragma", "no-cache");
        httpHeaders.add("Expires", "0");

        ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(httpHeaders).
                contentLength(file.length()).
                contentType(MediaType.parseMediaType("application/txt")).body(inputStreamResource);

        return responseEntity;
    }

使用如下:

上传成功后,会在这个目录中存在文件:

项目打包下载地址:

https://github.com/fengfanchen/Java/tree/master/SpringBootFileHandling

 

下面来分析下这个过程:

使用Fiddler抓包如下:

上传文件

从中可以看到,content-type为multipart/formdata其中边界分隔符为后面那个。他传的其实是二进制。

content-Disposition为内容倾向,为表单数据,name为程序中需要提交的键,filename为文件名。

下面的行,就是文件内容了。

 

下面来看看下载:

输入URL会激活IDM的下载

Fiddler下载如下:

这里的返回为Content-Disposition:为attachment说明是附件以及filename="cff.pdf",很多浏览器就是根据这条来判断,是文件的。

如果没有这条,就不会激发浏览器的下载。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT1995

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值