我对 PDF 下载的要求是:
- 当用户点击“下载”链接时,前端会将 JSON 数据POST到后端。
- 后端将处理 JSON,并根据其参数生成 PDF 文件。
- 作为响应,我(后端)需要发送下载链接和唯一文档 ID。
- 前端将在新窗口中打开该链接(GET),该链接将到达后端并开始下载。
我应该怎么做?
提前致谢。
最佳答案
如果您使用 Spring,则创建一个 Controller
@Controller
@RequestMapping(value = "/report")
public class ReportController {
@Autowired
ReportFileStore reportFileStore;
@RequestMapping(value = "/download/{uniqueId}", method = RequestMethod.GET)
public void getFile(@PathVariable("uniqueId") String uniqueId, HttpServletResponse response) {
//Find the generated PDF from somewhere, might be a disk, or RAM
byte[] pdf = getFromStore(uniqueId);
writeToResponse(pdf,response);
deleteFileFromStore(uniqueId);
}
private byte[] getFromStore(String uniqueId){
return reportFileStore.getFile(uniqueId);
}
}
方法writeToResponse
是一个标准的servlet下载代码,你可以看一个例子here或here .
关于getFromStore
,这是一个简单的方法,获取Jasper生成的PDF的byte[],当您生成时,您可以使用put方法来存储带有uniqueId的byte[]。
我会使用这样的界面
public interface ReportFileStore {
void storeFile(String uniqueId,byte[] content);
byte[] getFile(String uniqueId);
InputStream getFile(String uniqueId);
void deleteFile(String uniqueId);
}
并使用映射到 RAM 或磁盘上的 VFS 来实现它。
<小时/>当然,在生成PDF时,您需要为其生成一个唯一的ID,您可以尝试使用UUID 。将此 UUID 与 ReportFileStore
结合使用来保存 PDF 文件。目前尚不清楚“需要返回下载链接和唯一id”是否可以仅返回uniqueId,然后在前端硬编码下载位置。如果没有,则返回映射它的 JSON。
关于java - 在java中的新窗口中下载PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31138312/