接口响应头content-type为application/pdf;charset=UTF-8,将pdf文件存放于响应体里。

今天接到一个新的需求,客户为了方便定时把pdf文件从一台服务器传到另一台服务器上,自己制定了一套爬虫程序,要求我这边提供文件的下载接口,要求把pdf文件存放于响应体里方便直接下载。

话不多说,直接上代码。 

import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@RestController("/pdf/)
public class PdfController {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadPdf(Sting path){
        File file = new File(path);

        // 确保文件存在
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 设置输入流读取文件
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        ResponseEntity<InputStreamResource> response;
        try {
             String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()).replace("+", "%20");
             String contentDisposition = "attachment; filename=" + encodedFileName;
             response = ResponseEntity
                        .ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                       .contentType(MediaType.parseMediaType("application/pdf;charset=UTF-8"))
                        .body(new InputStreamResource(resource));
         } catch (FileNotFoundException e) {
                            throw new SysErrorException("文件不存在");
         } catch (UnsupportedEncodingException unsupportedEncodingException){
                            throw new SysErrorException("文件编码错误");
                        }
         return response;
    }
}

 这样就可以直接通过调用接口直接下载文件了,值得注意的是设置响应头Content-Disposition时attachment来指示浏览器这是一个需要下载的文件(直接在浏览器中打开为inline)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值