Is it possible to download a file with HTTP POST? I know the \"Get\" way(windows.location), but in my case, there are a lot of param that should be passed to server
I managed to solve it using this:
service.js
downloadExcel : function() {
var mapForm = document.createElement("form");
mapForm.target ="_self"||"_blank";
mapForm.id="stmtForm";
mapForm.method = "POST";
mapForm.action = "your_Controller_URL";
var mapInput = document.createElement("input");
mapInput.type = "hidden";
mapInput.name = "Data";
mapForm.appendChild(mapInput);
document.body.appendChild(mapForm);
mapForm.submit();
}
Spring Controller Code :
@Controller
@PostMapping(value = "/your_Controller_URL")
public void doDownloadEmsTemplate( final HttpServletRequest request, final HttpServletResponse response)
throws IOException, URISyntaxException {
String filePath = "/location/zzzz.xls";
logger.info("Excel Template File Location Path :" + filePath);
final int BUFFER_SIZE = 4096;
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
String fullPath = appPath + filePath;
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
//mimeType = "application/octet-stream";
mimeType = "application/vnd.ms-excel";
}
logger.info("MIME type: " + mimeType);
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
logger.info("File Download Successfully : ");
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}