java文件流接口javascript
package com.rainmanqqst.controller.filestream; import com.Ostermiller.util.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * @author RAINMANQQST * @date 2019-07-15 14:52 * @description */ @RestController @RequestMapping("/fille") public class FileController { private static Logger logger = LoggerFactory.getLogger(FileController.class); /** * 將直接資源請求接口地址轉爲文件流接口 * filePath爲base64加密的文件地址 * @param filePath * @param request * @param response */ @RequestMapping(value="/resource/{filePath}") public void achieveResource(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response){ try { String path = Base64.decode(filePath); logger.info("resource path is "+path); File file = new File(filePath); logger.info("fileName : "+file.getName()); response.setHeader("Content-disposition", "attachment; filename="+file.getName()); response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Length",file.length()+""); InputStream inputStream = new FileInputStream(file); ServletOutputStream servletOutputStream = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while((len=inputStream.read(buffer))>0){ servletOutputStream.write(buffer, 0, len); } servletOutputStream.flush(); inputStream.close(); servletOutputStream.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
JS下載代碼html
<html> <head> <%--<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">--%> <script type="text/javascript"> function exportFile() { // name=文件名, blob=文件二進制對象 // 獲取時間戳 var timestamp=new Date().getTime(); // 獲取XMLHttpRequest var xmlResquest = new XMLHttpRequest(); // 發起請求 xmlResquest.open("POST", "http://localhost:8086/rainmanqqst/api/system/resource/aHR0cHM6Ly9pbWcxLmRvdWJhbmlvLmNvbS92aWV3L3Bob3RvL2wvcHVibGljL3AxNDIyMDcxNjA4LndlYnA=", true); // 設置請求頭類型 xmlResquest.setRequestHeader("Content-type", "application/json"); // 設置請求token //xmlResquest.setRequestHeader( // "Authorization", // Vue.cookie.get('token') //); xmlResquest.responseType = "blob"; // 返回 xmlResquest.onload = function(oEvent) { var content = xmlResquest.response; alert(content); // 組裝a標籤 var elink = document.createElement("a"); // 設置下載文件名 elink.download = timestamp + ".png"; elink.style.display = "none"; var blob = new Blob([content]); elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); document.body.removeChild(elink); }; xmlResquest.send(); } </script> </head> <body> <input onclick="javascript:exportFile()" type="button" value="test" > </body> </html>