我有这样的服务
@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/reports")
public Response exportCSV(Map<String,List<String>> criteria) {
Response response = null;
if (userId != null) {
response = Response
.ok("Test Data".toByteArray(), MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition",
"attachment; filename=\"Sample_report.csv\"")
.build();
} else {
response = Response.noContent().build();
}
return response;
}
我的UI端代码是
var exportService = new Downloadreport ();
exportService.exportReport();
和Downloadreport代码看起来像这样
define([
'backbone'
], function(
Backbone
){
var Downloadreport = Backbone.Model.extend({
url: 'http://localhost:8080/services/reports',
exportReport: function() {
this.save({}, {
data: JSON.stringify("Some valid test data"),
dataType: 'text',
contentType: 'application/json',
type: 'POST',
success: function(model, response){
// Create a new Blob object using the
//response data of the onload object
var blob = new Blob([response], {type: 'text/csv'});
//Create a link element, hide it, direct
//it towards the blob, and then 'click' it programatically
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
//Create a DOMString representing the blob
//and point the link element towards it
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'Sample_report.csv';
//programatically click the link to trigger the download
a.click();
//release the reference to the file by revoking the Object URL
window.URL.revokeObjectURL(url);
}
});
console.log("POSTing stuff");
}
});
return Downloadreport;
});
当我测试我的UI时,我看到正确的响应即将到来(我可以在我的http POST请求的Response头中看到)。 但我希望下载一个CSV文件。这没有发生。 当我使用Adv REST客户端测试我的服务时,我看到了正确的响应,但我不确定是否可以使用REST客户端测试文件下载。 任何帮助表示赞赏
UPDATE2 :我通过添加成功回调并指示浏览器下载来解决此问题。这是一个正确的方法吗?上述方法是否在浏览器中保存文件内容?这种方法对更大的下载有害吗?
答案 0 :(得分:0)
UPDATE2:我通过添加成功回调并指示浏览器下载来管理此问题。 这是一个正确的方法吗? 上述方法是否在浏览器中保存文件内容? 这种方法对更大的下载有害吗?
这是回调代码。
codeception.yml