您好,登錄后才能下訂單哦!
代碼
參數:
1.filePath:文件的絕對路徑(d:\download\a.xlsx)
2.fileName(a.xlsx)
3.編碼格式(GBK)
4.response、request不介紹了,從控制器傳入的http對象
代碼片.
//控制器 @RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD) public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception { boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request); if(is) System.out.println("成功"); else System.out.println("失敗"); } //下載方法 public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){ File f = new File(filePath); if (!f.exists()) { try { response.sendError(404, "File not found!"); } catch (IOException e) { e.printStackTrace(); } return false; } String type = fileName.substring(fileName.lastIndexOf(".") + 1); //判斷下載類型 xlsx 或 xls 現在只實現了xlsx、xls兩個類型的文件下載 if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){ response.setContentType("application/force-download;charset=UTF-8"); final String userAgent = request.getHeader("USER-AGENT"); try { if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE瀏覽器 fileName = URLEncoder.encode(fileName, "UTF8"); } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐瀏覽器 fileName = new String(fileName.getBytes(), "ISO8859-1"); } else { fileName = URLEncoder.encode(fileName, "UTF8");// 其他瀏覽器 } response.setHeader("Content-disposition", "attachment; filename=" + fileName); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); return false; } InputStream in = null; OutputStream out = null; try { //獲取要下載的文件輸入流 in = new FileInputStream(filePath); int len = 0; //創建數據緩沖區 byte[] buffer = new byte[1024]; //通過response對象獲取outputStream流 out = response.getOutputStream(); //將FileInputStream流寫入到buffer緩沖區 while((len = in.read(buffer)) > 0) { //使用OutputStream將緩沖區的數據輸出到瀏覽器 out.write(buffer,0,len); } //這一步走完,將文件傳入OutputStream中后,頁面就會彈出下載框 } catch (Exception e) { logger.error(e.getMessage(), e); return false; } finally { try { if (out != null) out.close(); if(in!=null) in.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } return true; }else { logger.error("不支持的下載類型!"); return false; } }
實現效果
1.火狐瀏覽器效果
2.chrome效果,自動下載
補充知識:文件上傳/下載的幾種寫法(java后端)
文件上傳
1、框架已經幫你獲取到文件對象File了
public boolean uploadFileToLocale(File uploadFile,String filePath) { boolean ret_bl = false; try { InputStream in = new FileInputStream(uploadFile); ret_bl=copyFile(in,filePath); } catch (Exception e) { e.printStackTrace(); } return ret_bl; } public boolean copyFile(InputStream in,String filePath) { boolean ret_bl = false; FileOutputStream os=null; try { os = new FileOutputStream(filePath,false); byte[] b = new byte[8 * 1024]; int length = 0; while ((length = in.read(b)) > 0) { os.write(b, 0, length); } os.close(); in.close(); ret_bl = true; } catch (Exception e) { e.printStackTrace(); }finally{ try { if(os!=null){ os.close(); } if(in!=null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret_bl; } }
2、天了個擼,SB架構師根本就飄在天空沒下來,根本就沒想文件上傳這一回事
public String uploadByHttp(HttpServletRequest request) throws Exception{ String filePath=null; List<String> fileNames = new ArrayList<>(); //創建一個通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判斷 request 是否有文件上傳,即多部分請求 if(multipartResolver.isMultipart(request)){ //轉換成多部分request MultipartHttpServletRequest multiRequest =multipartResolver.resolveMultipart(request); MultiValueMap<String,MultipartFile> multiFileMap = multiRequest.getMultiFileMap(); List<MultipartFile> fileSet = new LinkedList<>(); for(Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()){ fileSet = temp.getValue(); } String rootPath=System.getProperty("user.dir"); for(MultipartFile temp : fileSet){ filePath=rootPath+"/tem/"+temp.getOriginalFilename(); File file = new File(filePath); if(!file.exists()){ file.mkdirs(); } fileNames.add(temp.getOriginalFilename()); temp.transferTo(file); } } }
3、神啊,我正在擼框架,請問HttpServletRequest怎么獲取!!!!
(1)在web.xml中配置一個監聽
<listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>
(2)HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
文件下載(直接用鏈接下載的不算),這比較簡單
1、本地文件下載(即文件保存在本地)
public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception { response.setCharacterEncoding("UTF-8"); //設置ContentType字段值 response.setContentType("text/html;charset=utf-8"); //通知瀏覽器以下載的方式打開 response.addHeader("Content-type", "appllication/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename="+fileName); //通知文件流讀取文件 InputStream in = request.getServletContext().getResourceAsStream(filePath); //獲取response對象的輸出流 OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; //循環取出流中的數據 while((len = in.read(buffer)) != -1){ out.write(buffer,0,len); } }
2、遠程文件下載(即網上資源下載,只知道文件URI)
public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){ try { urlStr=urlStr.replaceAll("\\\\", "/"); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //設置超時間為3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403錯誤 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到輸入流 InputStream inputStream = conn.getInputStream(); response.reset(); response.setContentType("application/octet-stream; charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1")); //獲取響應報文輸出流對象 //獲取response對象的輸出流 OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; //循環取出流中的數據 while((len = in.read(buffer)) != -1){ out.write(buffer,0,len); } } catch (Exception e) { e.printStackTrace(); } }
以上這篇Java后臺Controller實現文件下載操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。