试试这段代码,它是 jee 而不是 spring,但我认为它几乎相同
@GET
@Path("download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportScenario(@Context final HttpServletResponse resp) {
resp.setHeader("Cache-Control", "public");
resp.setHeader("Pragma", "public");
return Response.ok(new StreamingOutput() {
public void write(final OutputStream os) throws IOException {
// place to write file data into stream
}
}).header("Content-Disposition", "attachment; filename=\"file.zip\"").build();
}
更新:
浏览器端:
$.ajax({
url : 'rest/configuration/add.json',
type : 'POST',
contentType: 'application/json',
data : $.toJSON({
title : $('#conf_create_name')[0].value,
comment : $('#conf_create_comment')[0].value,
params : params
}),
});
带有 json 对象 $.toJSON 的 Ajax post reauset 需要额外的 jquery 插件搜索 google。
服务器端:
@POST
@Path("download")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportScenario(@Context final HttpServletResponse resp, final ConfigurationDTO confDTO) {
resp.setHeader("Cache-Control", "public");
resp.setHeader("Pragma", "public");
return Response.ok(new StreamingOutput() {
public void write(final OutputStream os) throws IOException {
// place to write file data into stream
}
}).header("Content-Disposition", "attachment; filename=\"file.zip\"").build();
}
配置DTO:
public class ConfigurationDTO {
private String title;
private String comment;
private Map<String, String> params;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
}