Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作
代碼
參數(shù):
1.filePath:文件的絕對(duì)路徑(d:downloada.xlsx)
2.fileName(a.xlsx)
3.編碼格式(GBK)
4.response、request不介紹了,從控制器傳入的http對(duì)象
代碼片.
//控制器@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 現(xiàn)在只實(shí)現(xiàn)了xlsx、xls兩個(gè)類型的文件下載 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;//創(chuàng)建數(shù)據(jù)緩沖區(qū)byte[] buffer = new byte[1024];//通過response對(duì)象獲取outputStream流out = response.getOutputStream();//將FileInputStream流寫入到buffer緩沖區(qū)while((len = in.read(buffer)) > 0) { //使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到瀏覽器 out.write(buffer,0,len);}//這一步走完,將文件傳入OutputStream中后,頁面就會(huì)彈出下載框 } 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; } }
實(shí)現(xiàn)效果
1.火狐瀏覽器效果
2.chrome效果,自動(dòng)下載
補(bǔ)充知識(shí):文件上傳/下載的幾種寫法(java后端)
文件上傳
1、框架已經(jīng)幫你獲取到文件對(duì)象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、天了個(gè)擼,SB架構(gòu)師根本就飄在天空沒下來,根本就沒想文件上傳這一回事
public String uploadByHttp(HttpServletRequest request) throws Exception{ String filePath=null; List<String> fileNames = new ArrayList<>(); //創(chuàng)建一個(gè)通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判斷 request 是否有文件上傳,即多部分請(qǐng)求 if(multipartResolver.isMultipart(request)){//轉(zhuǎn)換成多部分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、神啊,我正在擼框架,請(qǐng)問HttpServletRequest怎么獲取!!?。?/p>
(1)在web.xml中配置一個(gè)監(jiān)聽
<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'); //設(shè)置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對(duì)象的輸出流 OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; //循環(huán)取出流中的數(shù)據(jù) while((len = in.read(buffer)) != -1){ out.write(buffer,0,len); } }
2、遠(yuǎn)程文件下載(即網(wǎng)上資源下載,只知道文件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(); //設(shè)置超時(shí)間為3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403錯(cuò)誤 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'));//獲取響應(yīng)報(bào)文輸出流對(duì)象 //獲取response對(duì)象的輸出流 OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; //循環(huán)取出流中的數(shù)據(jù) while((len = in.read(buffer)) != -1){ out.write(buffer,0,len); } } catch (Exception e) { e.printStackTrace(); } }
以上這篇Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 什么是Python變量作用域2. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程3. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android studio 解決logcat無過濾工具欄的操作6. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式7. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼8. 一個(gè) 2 年 Android 開發(fā)者的 18 條忠告9. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析10. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼
