html代码
function dowmloadFile(id) {
var filename = "文件";
$.ajax({
url: "http://localhost:8080/interface/getFile",
type: "POST",
mimeType: "text/plain;charset=x-user-defined",
data: {
id: id
},
responseType: 'blob',
success: function (res) {
var rawLength = res.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (let index = 0; index < rawLength; index++) {
array[index] = res.charCodeAt(index) & 0xff;
}
var blob = new Blob([array], {type: "application/pdf;charset-UTF-8"});
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
}
else {
var blobURL = (window.URL && window.URL.createObjectURL) ? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob);
var tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
setTimeout(function () {
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}, 200)
}
}
})
}
java代码
@RequestMapping(value = "/getFile", method = RequestMethod.POST)
@ResponseBody
public void getFile(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) {
try {
ServletOutputStream out;
Detail article = interfaceService.getArticleById(id);
String url = article.getAccessory();
String name = article.getName();
URL url1 = new URL(Config.url + url);
URLConnection conn = url1.openConnection();
InputStream in = conn.getInputStream();
String afterName = url.substring(url.lastIndexOf(".") + 1);
response.setContentType(conn.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name + "." + afterName, "UTF-8"));
response.setCharacterEncoding("UTF-8");
int len;
byte[] buffer = new byte[1024 * 10];
out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
response中,filename还是乱码,不过无所谓了,实现了下载就行。