Is it possible to download a file with HTTP POST?

前端 未结 6 994
-上瘾入骨i
-上瘾入骨i 2020-12-15 16:37

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

6条回答
  •  清酒与你
    2020-12-15 17:17

    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();
        }
    

提交回复
热议问题