我正在尝试在控制器上下载base64编码文件。以下是我在几家谷歌商店推出的代码。
byte[] dataBytes = "QkVHSU46VkNBTEVOREFSDQpWRVJTSU9OOjIuMA0KTUVUSE9EOlBVQkxJU0gNClBST0RJRDotLy9DaXRyaXggT25saW5lLy9Hb1RvV2ViaW5hci8vRU4NClgtTVMtT0xLLUZPUkNFSU5TUEVDVE9ST1BFTjpUUlVFDQpCRUdJTjpWVElNRVpPTkUNClRaSUQ6QW1lcmljYS9Mb3NfQW5nZWxlcw0KVFpVUkw6aHR0cDovL3R6dXJsLm9yZy96b25laW5mby1vdXRsb29rL0FtZXJpY2EvTG9zX0FuZ2VsZXMNClgtTElDLUxPQ0FUSU9OOkFtZXJpY2EvTG9zX0FuZ2VsZXMNCkJFR0lOOkRBWUxJR0hUDQpUWk9GRlNFVEZST006LTA4MDANClRaT0ZGU0VUVE86LTA3MDANClRaTkFNRTpQRFQNCkRUU1RBUlQ6MTk3MDAzMDhUMDIwMDAwDQpSUlVMRTpGUkVRPVlFQVJMWTtCWU1PTlRIPTM7QllEQVk9MlNVDQpFTkQ6REFZTElHSFQNCkJFR0lOOlNUQU5EQVJEDQpUWk9GRlNFVEZST006LTA3MDANClRaT0ZGU0VUVE86LTA4MDANClRaTkFNRTpQU1QNCkRUU1RBUlQ6MTk3MDExMDFUMDIwMDAwDQpSUlVMRTpGUkVRPVlFQVJMWTtCWU1PTlRIPTExO0JZREFZPTFTVQ0KRU5EOlNUQU5EQVJEDQpFTkQ6VlRJTUVaT05FDQpCRUdJTjpWRVZFTlQNCkRUU1RBTVA6MjAxNzA0MjBUMjExMDM0Wg0KRFRTVEFSVDtUWklEPUFtZXJpY2EvTG9zX0FuZ2VsZXM6MjAxNzA0MjVUMTAwMDAwDQpEVEVORDtUWklEPUFtZXJpY2EvTG9zX0FuZ2VsZXM6MjAxNzA0MjVUMTEwMDAwDQpTVU1NQVJZOkdvVG9XZWJpbmFyIC0gTW9kZWxpbmcgYW5kIFF1ZXJ5aW5nIERhdGEg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TQ1JJUFRJT046UmVtaW5kZXINCkVORDpWQUxBUk0NCkVORDpWRVZFTlQNCkVORDpWQ0FMRU5EQVINCg==".getBytes();
Utilities.downloadFile(response, "application/pdf",
"Filename.pdf", dataBytes);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName +"."+ fileType);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
InputStream is = new ByteArrayInputStream(decodedDocument.getBytes(StandardCharsets.UTF_8));
FileCopyUtils.copy(is, response.getOutputStream());
response.flushBuffer();
这很好,并且在ajax上返回成功但没有显示下载弹出窗口或者没有在浏览器上下载文件。任何帮助表示赞赏。
添加Js功能。
/**
* DownloadFile
* When clicked on download file, execute this.
*/
downloadFile: function(patientId, attachmentId ) {
window.location.href = '/patient/details/attachments/download/' + patientId + '/' + attachmentId;
}
由于
答案 0 :(得分:0)
您无法通过ajax请求启动下载! Here you can find detail answer。
但是提供的插件依赖于浏览器
正如您希望通过浏览器下载,因此您需要通过<a href="'/patient/details/attachments/download/{patientId}/{attachmentId}">Download</a>
答案 1 :(得分:0)
在发送encodedDocument而不是String的字节后,文件开始下载而没有被破坏。
/* Set the file properties*/
if(fileType == null) {
response.setContentType("application/octet-stream");
} else {
response.setContentType(fileType);
}
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
/* Convert bytes to stream of objects*/
InputStream is = new ByteArrayInputStream(decodedDocument);
/*Download copying the content to destination file*/
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();