色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作

瀏覽:4日期:2022-08-23 10:12:47

代碼

參數(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中后,頁(yè)面就會(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.火狐瀏覽器效果

Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作

2.chrome效果,自動(dòng)下載

Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作

補(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怎么獲取!!!!

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

文件下載(直接用鏈接下載的不算),這比較簡(jiǎn)單

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)文件下載操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 欧美日韩亚洲国产精品 | 精品在线视频观看 | 7777在线 | 国产成人盗拍精品免费视频 | 成人性毛片 | 中国一级特黄真人毛片 | 久久综合伊人77777 | 日韩美女大全视频在线 | 国产精品91av | 国产成人精品一区二区三区 | 国产成人精品在视频 | 欧美最大成人毛片视频网站 | 性色欧美xo影院 | 九九久久久久午夜精选 | 真正免费一级毛片在线播放 | 久久99精品热在线观看15 | 欧美成人高清手机在线视频 | 国内自拍tv在线 | 边接电话边做国语高清对白 | 免费一级 一片一毛片 | 国产精品久久久久一区二区三区 | 一个人看的免费高清视频日本 | 久久国产精品-久久精品 | 久久91精品国产91久久 | 国产成人精品视频 | 日本一级看片免费播放 | 久草在线视频免费看 | 欧美在线不卡 | 狠狠色丁香久久婷婷综合_中 | 久青草网站 | 亚洲国产www| 欧美一级一一特黄 | 一区在线视频 | 日韩中文在线观看 | 免费国产不卡午夜福在线 | 欧洲亚洲一区二区三区 | 日本免费在线视频 | 99久久久免费精品免费 | 亚洲男人的性天堂 | 国产三香港三韩国三级不卡 | 在线国产三级 |