本地单文件下载
Swagger測試中文會出現亂碼,復制路徑新的連接打開可能就不是亂碼
第一種方式
/*** 下載*/@GetMapping(value = "/download")@ApiOperation(value = "下載(管理端也可用)")public void download(String name,String path,HttpServletRequest request, HttpServletResponse response) {try {// path是指想要下載的文件的路徑File file = new File("D:/image/"+path);// 獲取文件名String filename = file.getName();// 獲取文件后綴名String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();// 將文件寫入輸入流FileInputStream fileInputStream = new FileInputStream(file);InputStream fis = new BufferedInputStream(fileInputStream);byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 設置response的Header/* if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {name = java.net.URLEncoder.encode(name, "UTF-8");} else {//非IE瀏覽器的處理:name = new String(name.getBytes("UTF-8"), "ISO-8859-1");}*/response.setCharacterEncoding("UTF-8");//Content-Disposition的作用:告知瀏覽器以何種方式顯示響應返回的文件,用瀏覽器打開還是以附件的形式下載到本地保存//attachment表示以附件方式下載 inline表示在線打開 "Content-Disposition: inline; filename=文件名.mp3"// filename表示文件的默認名稱,因為網絡傳輸只支持URL編碼的相關支付,因此需要將文件名URL編碼后進行傳輸,前端收到后需要反編碼才能獲取到真正的名稱response.addHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(name, "UTF-8"))) + '.' + ext);// 告知瀏覽器文件的大小response.addHeader("Content-Length", "" + file.length());OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream;charset=UTF-8");outputStream.write(buffer);outputStream.flush();} catch (IOException ex) {ex.printStackTrace();}}第二種方式
//downloadName 是下載后文件名稱用來中文處理//pdfCreate+waterName 是下載的路徑if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");} else {//非IE瀏覽器的處理:downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + downloadName + "\"");FileInputStream fileInputStream = null;fileInputStream = new FileInputStream(pdfCreate+waterName);IoUtil.copy(fileInputStream , response.getOutputStream());fileInputStream.close();總結
- 上一篇: 懒惰(Laziness)、急躁(Impa
- 下一篇: mac下安装使用switchyomega