今天接到一个新的需求,客户为了方便定时把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)。