I want to download without screen transition, but I was a little disappointed to use the HttpResponseHeader class, so I implemented it using only the Spring package class. Note that the client-side implementation is likely to be forgotten.
Controller
@RequestMapping("/download")
@ResponseBody
public ResponseEntity<byte[]> download() {
byte[] data = xxx; // xxx:byte[]Format object
// ResponseHeader
HttpHeaders header = new HttpHeaders();
header.add("Content-Type", "yyy"); // yyy:Any Content-Type
header.add("Content-Disposition", "attachment; filename*=utf-8''" + URLEncoder.encode("zzz", "UTF-8")); // zzz:Arbitrary file name
header.add("Set-Cookie", "fileDownload=true; path=/");
return new ResponseEntity<byte[]>(data, header, HttpStatus.OK);
}
javascript
//Add event when submitting form
$("#myform").submit(function() {
startLoading(); //Round and round method
const COOKIE_KEY_FILEDOWNLOAD = 'fileDownload=';
var isFileDownload = false;
//Repeat until download is complete
var intervalId = setInterval(function() {
//Get fileDownload from cookie
const COOKIES = document.cookie;
var position = COOKIES.indexOf(COOKIE_KEY_FILEDOWNLOAD);
if (position >= 0) {
var startIdx = position + COOKIE_KEY_FILEDOWNLOAD.length;
var endIdx = COOKIES.indexOf(';', startIdx);
if (endIdx < 0) {
endIdx = COOKIES.length;
}
isFileDownload = decodeURIComponent(COOKIES.substring(startIdx, endIdx)) == 'true';
}
//If fileDownload is true, it ends repeatedly
if (isFileDownload) {
clearInterval(intervalId);
var date = new Date();
date.setTime(date.getTime() - 1);
document.cookie = COOKIE_KEY_FILEDOWNLOAD + 'false; path=/; max-age=0';
stopLoading(); //A method to stop round and round
}
}, 500);
});
Recommended Posts