Java实现简单文件下载
- 格式:docx
- 大小:16.16 KB
- 文档页数:3
java实现从url路径中下载pdf⽂档到本地package com.cellstrain.icell.util;import java.io.*;import .*;public class DownloadPdf {/*** 从⽹络Url中下载⽂件* @param urlStr* @param fileName* @param savePath* @throws IOException*/public static void downLoadByUrl(String urlStr,String fileName,String savePath) throws IOException{URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection)url.openConnection();//设置超时间为3秒conn.setConnectTimeout(5*1000);//防⽌屏蔽程序抓取⽽返回403错误conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");//得到输⼊流InputStream inputStream = conn.getInputStream();//获取⾃⼰数组byte[] getData = readInputStream(inputStream);//⽂件保存位置File saveDir = new File(savePath);if(!saveDir.exists()){saveDir.mkdir();}File file = new File(saveDir+File.separator+fileName);FileOutputStream fos = new FileOutputStream(file);fos.write(getData);if(fos!=null){fos.close();}if(inputStream!=null){inputStream.close();}System.out.println("info:"+url+" download success");}/*** 从输⼊流中获取字节数组* @param inputStream* @return* @throws IOException*/public static byte[] readInputStream(InputStream inputStream) throws IOException {byte[] buffer = new byte[1024];int len = 0;ByteArrayOutputStream bos = new ByteArrayOutputStream();while((len = inputStream.read(buffer)) != -1) {bos.write(buffer, 0, len);}bos.close();return bos.toByteArray();}public static void main(String[] args) {try{downLoadByUrl("https:///images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_Protocol.pdf", "ELISA.pdf","E:/upload/protocol");}catch (Exception e) {// TODO: handle exception}}}详细介绍请查看全⽂:。
java后台实现excel⽂件下载功能 java中对于excel⽂件的操作,有读取,写⼊,上传等功能,在对excel⽂件进⾏操作时,为了让使⽤者更加直观的制作excel数据,必然会有下载模板excel⽂件功能,这⾥以学⽣基本信息模板excel⽂件为例,实现对指定路径下的excel⽂件进⾏下载的后台代码。
对excel⽂件的操作使⽤到poi接⼝,对于不同拓展名的excel⽂件调⽤不同的对象,maven导⼊jar包语句可以参考。
我们在这⾥操作的对象是.xlsx格式的excel⽂件。
代码如下:/*** 学⽣excel模板下载,可⽤于批量新建,修改学⽣对象,** @param response* @param request* @return*/@RequestMapping(value = "downLoadStuInfoExcel", produces = "text/html;charset=UTF-8")public void downLoadStuInfoExcel(HttpServletResponse response, HttpServletRequest request) {JSONObject rt = new JSONObject();//json对象,⽤来记录下载状态值,写⼊log中,也可以把状态值返回到前台,这⼀部分可有可⽆。
rt.put("status", "1");rt.put("message", "");rt.put("result", "");//学⽣新建excel下载模板保存地址从配置⽂件中读取String folderPath = ResourceBundle.getBundle("systemconfig").getString("stuExcelDownLoadPath") + File.separator + "stuTemplateExcel.xlsx";File excelFile = new File(folderPath);//判断模板⽂件是否存在if (!excelFile.exists() || !excelFile.isFile()) {rt.put("status", "0");rt.put("message", "模板⽂件不存在");// return rt.toJSONString();}//⽂件输⼊流FileInputStream fis = null;XSSFWorkbook wb = null;//使⽤XSSFWorkbook对象读取excel⽂件try {fis = new FileInputStream(excelFile);wb = new XSSFWorkbook(fis);fis.close();} catch (Exception e) {e.printStackTrace();rt.put("status", "0");rt.put("message", "模板⽂件读取失败");// return rt.toJSONString();}//设置contentType为vnd.ms-excelresponse.setContentType("application/vnd.ms-excel;charset=utf-8");response.setCharacterEncoding("utf-8");// 对⽂件名进⾏处理。
Java实现浏览器下载⽂件及⽂件预览插曲想记录⼀下,以后可以来粘贴复制⽤。
⼀、浏览器下载⽂件setContentType() 该实体头的作⽤是让服务器告诉浏览器它发送的数据属于什么⽂件类型。
没有缓存response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");public static void setResponseHeader(HttpServletResponse response, String name) {try {name = new String(name.getBytes(), "ISO8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setContentType("application/docx");//要保存的⽂件名response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");}⼆、浏览器预览⽂件只需要把下⾯这⾏注释就好response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");setContentType() 中的参数选择:⽂件扩展名Content-Type(Mime-Type)⽂件扩展名Content-Type(Mime-Type).*(⼆进制流,不知道下载⽂件类型)application/octet-stream.tif image/tiff.001application/x-001.301application/x-301.323text/h323.906application/x-906.907drawing/907.a11application/x-a11.acp audio/x-mei-aac.ai application/postscript.aif audio/aiff.aifc audio/aiff.aiff audio/aiff.anv application/x-anv.asa text/asa.asf video/x-ms-asf.asp text/asp.asx video/x-ms-asf.au audio/basic.avi video/avi.awf application/ text/xml.bmp application/x-bmp.bot application/x-bot.c4t application/x-c4t.c90application/x-c90.cal application/x-cals.cat application/vnd.ms-pki.seccat .cdf application/x-netcdf.cdr application/x-cdr.cel application/x-cel.cer application/x-x509-ca-cert.cg4application/x-g4.cgm application/x-cgm.cit application/x-cit.class java/*.cml text/xml.cmp application/x-cmp.cmx application/x-cmx.cot application/x-cot.crl application/pkix-crl.crt application/x-x509-ca-cert.csi application/x-csi.css text/css.cut application/x-cut.dbf application/x-dbf.dbm application/x-dbm.dbx application/x-dbx.dcd text/xml.dcx application/x-dcx.der application/x-x509-ca-cert.dgn application/x-dgn.dib application/x-dib.dll application/x-msdownload.doc application/msword.dot application/msword.drw application/x-drw.dtd text/xml.dwf Model/vnd.dwf.dwf application/x-dwf.dwg application/x-dwg.dxb application/x-dxb.dxf application/x-dxf.edn application/vnd.adobe.edn.emf application/x-emf.eml message/rfc822.ent text/xml.epi application/x-epi.eps application/x-ps.eps application/postscript.etd application/x-ebx.exe application/x-msdownload.fax image/fax.fdf application/vnd.fdf.fif application/fractals.fo text/xml.frm application/x-frm.g4application/x-g4.gbr application/x-gbr.application/x-.gif image/gif.gl2application/x-gl2.gp4application/x-gp4.hgl application/x-hgl.hmr application/x-hmr.hpg application/x-hpgl.hpl application/x-hpl.hqx application/mac-binhex40.hrf application/x-hrf.hta application/hta.htc text/x-component.htm text/html.html text/html.htt text/webviewhtml.htx text/html.icb application/x-icb.ico image/x-icon.ico application/x-ico.iff application/x-iff.ig4application/x-g4.igs application/x-igs.iii application/x-iphone.img application/x-img.ins application/x-internet-signup .isp application/x-internet-signup.IVF video/x-ivf.java java/*.jfif image/jpeg.jpe image/jpeg.jpe application/x-jpe.jpeg image/jpeg.jpg image/jpeg.jpg application/x-jpg.js application/x-javascript.jsp text/1audio/x-liquid-file.lar application/tex application/x-latex.lavs audio/x-liquid-secure.lbm application/x-lbm.lmsff audio/x-la-lms.ls application/x-javascript.ltr application/x-ltr.m1v video/x-mpeg.m2v video/x-mpeg.m3u audio/mpegurl.m4e video/mpeg4.mac application/x-mac.man application/x-troff-man.math text/xml.mdb application/msaccess.mdb application/x-mdb.mfp application/x-shockwave-flash.mht message/rfc822.mhtml message/rfc822.mi application/x-mi.mid audio/mid.midi audio/mid.mil application/x-mil.mml text/xml.mnd audio/x-musicnet-download.mns audio/x-musicnet-stream.mocha application/x-javascript.movie video/x-sgi-movie.mp1audio/mp1.mp2audio/mp2.mp2v video/mpeg.mp3audio/mp3.mp4video/mpeg4.mpa video/x-mpg.mpd application/vnd.ms-project.mpe video/x-mpeg.mpeg video/mpg.mpg video/mpg.mpga audio/rn-mpeg.mpp application/vnd.ms-project.mps video/x-mpeg.mpt application/vnd.ms-project.mpv video/mpg.mpv2video/mpeg.mpw application/vnd.ms-project.mpx application/vnd.ms-project.mtx text/xml.mxp application/x-mmxp.net image/pnetvue.nrf application/x-nrf.nws message/rfc822.odc text/x-ms-odc.out application/x-out.p10application/pkcs10.p12application/x-pkcs12.p7b application/x-pkcs7-certificates .p7c application/pkcs7-mime.p7m application/pkcs7-mime.p7r application/x-pkcs7-certreqresp.p7s application/pkcs7-signature.pc5application/x-pc5.pci application/x-pci.pcl application/x-pcl.pcx application/x-pcx.pdf application/pdf.pdf application/pdf.pdx application/vnd.adobe.pdx.pfx application/x-pkcs12.pgl application/x-pgl.pic application/x-pic.pko application/vnd.ms-pki.pko.pl application/x-perl.plg text/html.pls audio/scpls.plt application/x-plt.png image/png.png application/x-png.pot application/vnd.ms-powerpoint .ppa application/vnd.ms-powerpoint.ppm application/x-ppm.pps application/vnd.ms-powerpoint.ppt application/vnd.ms-powerpoint .ppt application/x-ppt.pr application/x-pr.prf application/pics-rules.prn application/x-prn.prt application/x-prt.ps application/x-ps.ps application/postscript.ptn application/x-ptn.pwz application/vnd.ms-powerpoint.r3t text/vnd.rn-realtext3d.ra audio/vnd.rn-realaudio.ram audio/x-pn-realaudio.ras application/x-ras.rat application/rat-file.rdf text/xml.rec application/vnd.rn-recording.red application/x-red.rgb application/x-rgb.rjs application/vnd.rn-realsystem-rjs.rjt application/vnd.rn-realsystem-rjt .rlc application/x-rlc.rle application/x-rle.rm application/vnd.rn-realmedia.rmf application/vnd.adobe.rmf.rmi audio/mid.rmj application/vnd.rn-realsystem-rmj.rmm audio/x-pn-realaudio.rmp application/vnd.rn-rn_music_package.rms application/vnd.rn-realmedia-secure.rmvb application/vnd.rn-realmedia-vbr .rmx application/vnd.rn-realsystem-rmx.rnx application/vnd.rn-realplayer.rp image/vnd.rn-realpix.rpm audio/x-pn-realaudio-plugin.rsml application/vnd.rn-rsml.rt text/vnd.rn-realtext.rtf application/msword.rtf application/x-rtf.rv video/vnd.rn-realvideo.sam application/x-sam.sat application/x-sat.sdp application/sdp.sdw application/x-sdw.sit application/x-stuffit.slb application/x-slb.sld application/x-sld.slk drawing/x-slk.smi application/smil.smil application/smil.smk application/x-smk.snd audio/basic.sol text/plain.sor text/plain.spc application/x-pkcs7-certificates .spl application/futuresplash.spp text/xml.ssm application/streamingmedia.sst application/vnd.ms-pki.certstore .stl application/vnd.ms-pki.stl.stm text/html.sty application/x-sty.svg text/xml.swf application/x-shockwave-flash.tdf application/x-tdf.tg4application/x-tg4.tga application/x-tga.tif image/tiff.tif application/x-tif.tiff image/tiff.tld text/xml.top drawing/x-top.torrent application/x-bittorrent.tsd text/xml.txt text/plain.uin application/x-icq.uls text/iuls.vcf text/x-vcard.vda application/x-vda.vdx application/vnd.visio.vml text/xml.vpg application/x-vpeg005.vsd application/vnd.visio.vsd application/x-vsd.vss application/vnd.visio.vst application/vnd.visio.vst application/x-vst.vsw application/vnd.visio.vsx application/vnd.visio.vtx application/vnd.visio.vxml text/xml.wav audio/wav.wax audio/x-ms-wax.wb1application/x-wb1.wb2application/x-wb2.wb3application/x-wb3.wbmp image/vnd.wap.wbmp.wiz application/msword.wk3application/x-wk3.wk4application/x-wk4.wkq application/x-wkq.wks application/x-wks.wm video/x-ms-wm.wma audio/x-ms-wma.wmd application/x-ms-wmd.wmf application/x-wmf.wml text/vnd.wap.wml.wmv video/x-ms-wmv.wmx video/x-ms-wmx.wmz application/x-ms-wmz.wp6application/x-wp6.wpd application/x-wpd.wpg application/x-wpg.wpl application/vnd.ms-wpl.wq1application/x-wq1.wr1application/x-wr1.wri application/x-wri.wrk application/x-wrk.ws application/x-ws.ws2application/x-ws.wsc text/scriptlet.wsdl text/xml.wvx video/x-ms-wvx.xdp application/vnd.adobe.xdp.xdr text/xml.xfd application/vnd.adobe.xfd.xfdf application/vnd.adobe.xfdf.xhtml text/html.xls application/vnd.ms-excel.xls application/x-xls.xlw application/x-xlw.xml text/xml.xpl audio/scpls.xq text/xml.xql text/xml.xquery text/xml.xsd text/xml.xsl text/xml.xslt text/xml.xwd application/x-xwd.x_b application/x-x_b.sis application/vnd.symbian.install.sisx application/vnd.symbian.install .x_t application/x-x_t.ipa application/vnd.iphone.apk application/vnd.android.package-archive.xap application/x-silverlight-appJava 后台字符串以txt⽂件响应到浏览器进⾏下载String fileName = "短信模版.txt";OutputStream os = null;try {response.reset();response.setContentType("application/octet-stream; charset=utf-8");response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO8859-1")); byte[] bytes = sb.toString().getBytes("GBK");os = response.getOutputStream();// 将字节流传⼊到响应流⾥,响应到浏览器os.write(bytes);os.close();} catch (Exception ex) {logger.error("导出失败:", ex);throw new RuntimeException("导出失败");}finally {try {if (null != os) {os.close();}} catch (IOException ioEx) {logger.error("导出失败:", ioEx);}}以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
Java从服务器下载⽂件到本地(页⾯、后台、配置都有)先来看实现效果:有⼀个链接如下:点击链接下载⽂件:第⼀种⽅法:Servlet实现⼀、HTML页⾯部分:1、HTML页⾯中的⼀个链接<a id="downloadTemplate" style="color:blue" onclick="download();">下载导⼊模板</a>2、引⼊JSfunction download(){downloadTemplate('downloadExel.downloadexcel', 'filename', 'project');}/*** ⽤于下载导⼊模板时的影藏form表单的提交,采⽤post⽅式提交* @param action action映射地址* @param type parameter的名称* @param value parameter的值,这⾥为file的filename*/function downloadTemplate(action, type, value){var form = document.createElement('form');document.body.appendChild(form);form.style.display = "none";form.action = action;form.id = 'excel';form.method = 'post';var newElement = document.createElement("input");newElement.setAttribute("type","hidden"); = type;newElement.value = value;form.appendChild(newElement);form.submit();}3、解释上⾯JS(不是正是代码)相当于提交⼀个form,⾥⾯如下:<input type=hidden name="filename" value = "project">后台可以通过下⾯代码获得⽂件名:projectString filename = request.getParameter("filename");(这段是上⾯js的翻译,不是正式的哦)配置前台页⾯和后台交互1、web.xml配置<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" version="2.4"xmlns="/xml/ns/j2ee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/j2ee /xml/ns/j2ee/web-app_2_4.xsd"><servlet><servlet-name>downloadServlet</servlet-name><servlet-class>com.zit.rfid.app.prms.business.service.servlet.DownloadTemplateServlet</servlet-class><load-on-startup>3</load-on-startup></servlet><servlet-mapping><servlet-name>downloadServlet</servlet-name><url-pattern>*.downloadexcel</url-pattern></servlet-mapping></web-app>我这个web.xml不是整个⼯程的web.xml,只是⼀个模块的,在你的web.xml加⼊上⾯servlet和servlet-mapping⾥的内容即可如上:(1)接受 *.downloadexcel 的Action(2)HTML的JS⾥的Action,交给com.test.DownloadTemplateServlet这个类去处理2、WebContent⽬录下新建file⽂件夹,存放project.xls⽂件(Eclipse的Web⼯程有WebContent,MyEclipse好像是WebRoot)三、后台部分1、新建⼀个servlet: DownloadTemplateServlet.javapackage com.test;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import .URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** @author 022******** 主要⽤于下载导⼊模板,页⾯上传⼊的request中parameter中,filename代表了要下载的模板的名称*/public class DownloadTemplateServlet extends HttpServlet {/**private static final long serialVersionUID = -4541729035831587727L;private final static String HOME_PATH = DownloadTemplateServlet.class.getResource("/").getPath();private final static String DOWNLOAD_TEMP_FILE = HOME_PATH.subSequence(0, HOME_PATH.indexOf("WEB-INF")) + "file/"; @Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String filename = req.getParameter("filename");try{resp.reset();// 清空输出流String resultFileName = filename + System.currentTimeMillis() + ".xls";resultFileName = URLEncoder.encode(resultFileName,"UTF-8");resp.setCharacterEncoding("UTF-8");resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出⽂件头resp.setContentType("application/msexcel");// 定义输出类型//输⼊流:本地⽂件路径DataInputStream in = new DataInputStream(new FileInputStream(new File(DOWNLOAD_TEMP_FILE + filename + ".xls")));//输出流OutputStream out = resp.getOutputStream();//输出⽂件int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}out.close();in.close();} catch(Exception e){e.printStackTrace();resp.reset();try {OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";writer.write(data);writer.close();} catch (IOException e1) {e1.printStackTrace();}}}}⼤致步骤:1. 获取服务器⽂件所在路径2. 输⼊服务器⽂件3. 输出⽂件到本地第⼆种⽅法:SpringMVC实现这种⽅法⽐较简单⼀、JSP页⾯部分<a id="downloadTemplate" style="color:blue" onclick="download();">下载导⼊模板</a>//导出模板下载function download(){//后台⽅法、⽂件类型、⽂件名downloadTemplate('${pageContext.request.contextPath}/cardIssueVehicleInfo/exportVehicleInfo', 'filename', 'test'); }/*** ⽤于下载导⼊模板时的影藏form表单的提交,采⽤post⽅式提交* @param action 请求后台⽅法* @param type ⽂件类型* @param value ⽂件名*/function downloadTemplate(action, type, value){var form = document.createElement('form');document.body.appendChild(form);form.style.display = "none";form.action = action;form.id = 'excel';form.method = 'post';var newElement = document.createElement("input");newElement.setAttribute("type","hidden"); = type;newElement.value = value;form.appendChild(newElement);form.submit();}⼆、后台部分@RequestMapping("exportVehicleInfo")public void exportVehicleInfo(HttpServletRequest req, HttpServletResponse resp) {String filename = req.getParameter("filename");DataInputStream in = null;OutputStream out = null;try{resp.reset();// 清空输出流String resultFileName = filename + System.currentTimeMillis() + ".xls";resultFileName = URLEncoder.encode(resultFileName,"UTF-8");resp.setCharacterEncoding("UTF-8");resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出⽂件头resp.setContentType("application/msexcel");// 定义输出类型//输⼊流:本地⽂件路径in = new DataInputStream(new FileInputStream(new File(downloadPath + "test.xls")));//输出流out = resp.getOutputStream();//输出⽂件int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}} catch(Exception e){e.printStackTrace();resp.reset();try {OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";writer.write(data);writer.close();} catch (IOException e1) {e1.printStackTrace();}}finally {if(null != in) {try {in.close();} catch (IOException e) {e.printStackTrace();}if(null != out) {try {out.close();} catch (IOException e) { e.printStackTrace(); }}}}。
tomcat上传文件下载文件首先介绍一下我们需要的环境:我用的是myeclipse8.5的java开发环境,tomcat是用的apache-tomcat-6.0.26这个版本。
首先先需要准备一下使用到的jar包这些jar包是struts2的jar包。
这些jar包是都是用于上传文件的。
注意:这里的jar包版本必须是对应的,如不是可能会tomcat下报错。
所以大家最好注意一下啊。
最好是用这套jar包。
我将会在csdn上将项目jar包发上去。
Jar下载地址(0分):/detail/woaixinxin123/4193113 源代码下载(10分):/detail/woaixinxin123/4193134开始搭建我们的项目。
创建web项目名字为File。
第一步:搭建struts2框架。
1、到jar包。
2、编辑web.xml<?xml version="1.0"encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><!-- 增加struts2的支持 --><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepa reAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>3、添加struts.xml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""/dtds/struts-2.0.dtd"><struts></struts>4、启动tomcat测试。
基于Java⽂件输⼊输出流实现⽂件上传下载功能本⽂为⼤家分享了Java实现⽂件上传下载功能的具体代码,供⼤家参考,具体内容如下前端通过form表单的enctype属性,将数据传递⽅式修改为⼆进制”流“的形式,服务端(servlet)通过 getInputStream() 获取流信息,运⽤java I/O 流的基础操作将流写⼊到⼀个服务端临时创建的⽂件temp中,然后再次利⽤⽂件基本操作,读取并截取临时⽂件内容,根据其中信息创建相应的⽂件,将读取出来的具体信息写⼊,下载时,根据提交的⽂件名称,找到服务器端相应的⽂件,然后根据输出流outStream输出到页⾯,同时将servlet的响应类型和响应头进⾏设置。
具体传输流程如下图:流信息的部分为:具体代码如下:前端代码:<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script src="Js/jquery.js"></script></head><body><form action="FileUpServlet" method="post" enctype="multipart/form-data"><table><tr><td>请选择上传⽂件:</td><td><input id="myfile" name="myfile" type="file" value="" /></td><td><input type="submit" value="上传"></td></tr><tr><td>${info}</td></tr></table></form>⽂件下载:<a href="FileLoadownServlet?filename=${filename}">${filename}</a></body></html>上传servlet部分(核⼼)@WebServlet("/FileUpServlet")public class FileUpServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public FileUpServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubdoPost(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubrequest.setCharacterEncoding("utf-8");InputStream filesource = request.getInputStream();//request获取流信息String tempname = "D:/temp";//tempfile代表临时存放⽂件File tempfile = new File(tempname);//创建临时⽂件FileOutputStream outputStream = new FileOutputStream(tempfile);//输出流对象,指定输出指tempfile⽬录下byte b[] = new byte[1024];int n;while((n = filesource.read(b))!= -1)//从输出流中每次读取1024字节,直⾄读完{outputStream.write(b,0,n);}outputStream.close();filesource.close();//关闭输⼊输出流/*以下为具体的⽂件操作,主要为解析临时产⽣的 temp⽂件,知识多为java输⼊输出流的内容!*/RandomAccessFile randomfile = new RandomAccessFile(tempfile, "r");//随机流,指定要读临时⽂件,只读randomfile.readLine();//读取第⼀⾏,⽆效数据,不需要String str = randomfile.readLine();//读取第⼆⾏int beginIndex = stIndexOf("=")+2;//指定所需数据的开始位置int endIndex = stIndexOf("\"");//指定所需数据截⾄位置String filename = str.substring(beginIndex,endIndex);//截取⽂件名//重新定位⽂件指针,获取⽂件内容randomfile.seek(0);//⽂件指针从头开始long startext = 0;int i = 1;//⽂件内容开始位置while((n=randomfile.readByte()) != -1&&i <= 4){if(n=='\n'){startext = randomfile.getFilePointer();i++;}}startext = randomfile.getFilePointer() - 1;//获取⽂件内容结束位置randomfile.seek(randomfile.length());long endtext = randomfile.getFilePointer();int j = 1;while(endtext >= 0 && j <= 2){endtext--;randomfile.seek(endtext);if(randomfile.readByte()=='\n'){j++;}}endtext = endtext-1;//将临时⽂件保存⾄指定⽬录中String realpath = getServletContext().getRealPath("/")+"images";//设置⽂件保存⽬录System.out.println(realpath);File fileupload = new File(realpath);if(!fileupload.exists()){fileupload.mkdir();//⽬录不存在则创建}File savefile = new File(realpath,filename);RandomAccessFile randomAccessFile = new RandomAccessFile(savefile, "rw");randomfile.seek(startext);while(startext<endtext){randomAccessFile.write(randomfile.readByte());//⽂件写⼊startext = randomfile.getFilePointer();}//关闭各种输⼊输出流randomAccessFile.close();randomfile.close();tempfile.delete();//删除临时⽂件SimpleDateFormat timed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date nowdate = new Date();String time = timed.format(nowdate.getTime());request.setAttribute("info", time+" "+filename+"上传成功!");request.setAttribute("filename", filename);request.getRequestDispatcher("/fildeOp.jsp").forward(request, response);}}下载部分protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubString filename = request.getParameter("filename");String path = getServletContext().getRealPath("/")+"images/";File file = new File(path+filename);//找到⽂件if(file.exists())response.setContentType("application/x-msdownload"); //设置响应类型,此处为下载类型response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");//以附件的形式打开 InputStream inputStream = new FileInputStream(file);ServletOutputStream outputStream = response.getOutputStream();byte b[] = new byte[1024];int n;while((n = inputStream.read(b)) != -1){outputStream.write(b,0,n);}outputStream.close();inputStream.close();}else{request.setAttribute("result", "⽂件不存在!下载失败!");request.getRequestDispatcher("/fildeOp.jsp").forward(request, response);}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java实现从⽹络下载多个⽂件java从⽹络下载多个⽂件,供⼤家参考,具体内容如下⾸先是打包下载多⽂件,即打成压缩包在下载。
其次别处的资源:可以是别的服务器,可以是⽹上的资源,当然也可以是本地的(更简单)最后:⼀次性下载,⼀次性下载多个⽂件三步⾛:⼀、先将 “别处” 需要下载的⽂件下载到服务器,然后将⽂件的路径改掉⼆、然后将服务器上的⽂件打成压缩包三、下载这个压缩包//下载@RequestMapping("/download01")public void downloadImage(String tcLwIds, HttpServletRequest request, HttpServletResponse response) throws Exception{ boolean dflag = false;String[] paths = tcLwIds.split(",");File [] file1 = new File[paths.length];DownLoadImageUtil imageUtils = new DownLoadImageUtil();if(paths.length > 1){for (int i = 0; i < paths.length; i++) {String imagepath=paths[i];imageUtils.makeImage(imagepath); //将url的图⽚下载到本地,这个⽅法在下边//修改为图⽚存放路径file1[i] = new File("D:/upload/"+imagepath.substring(stIndexOf("/")));}filesDown(request, response, file1);//这是下边的⼀个⽅法}}//将下载到服务器的图⽚放⼊压缩包public void filesDown(HttpServletRequest request,HttpServletResponse response,File[] file1 ) throws Exception {Random r=new Random();String tmpFileName =r.nextInt(10000) +"downImage.zip";String upath=request.getRealPath("/");upath=upath.substring(0,upath.length()-1);upath=upath.substring(0,stIndexOf("\\"));//服务地址的存放路径String FilePath = upath+"/ROOT/data/";File f=new File(FilePath);if(!f.exists()){ //路径不存在就创建FileUtil.createDir(FilePath);}byte[] buffer = new byte[1024];String strZipPath = FilePath + tmpFileName; //路径加⽂件名try {ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));for (int i = 0; i < file1.length; i++) {FileInputStream fis = new FileInputStream(file1[i]);out.putNextEntry(new ZipEntry(file1[i].getName()));//设置压缩⽂件内的字符编码,不然会变成乱码out.setEncoding("GBK");int len;// 读⼊需要下载的⽂件的内容,打包到zip⽂件while ((len = fis.read(buffer)) > 0) {out.write(buffer, 0, len);}out.closeEntry();fis.close();}out.close();//下载的服务地址根据实际情况修改boolean dflag = downloafile(request, response,"http://localhost:8080/data/"+tmpFileName);//将服务器上压缩前的源⽂件删除for (int i = 0; i < file1.length; i++) {if (file1[i].isFile()) {file1[i].delete();}}//将服务器上的压缩包删除File fileZip=new File(strZipPath);fileZip.delete();} catch (Exception e) {e.printStackTrace();}}//写到本地public boolean downloafile(HttpServletRequest request,HttpServletResponse response, String path) { String name = path.substring(stIndexOf("/")+1);String filename = DownLoadImageUtil.encodeChineseDownloadFileName(request, name);response.setHeader("Content-Disposition", "attachment; filename=" + filename + ";");boolean flag = false;try {URL url = new URL(path);InputStream inStream = url.openConnection().getInputStream();BufferedInputStream in = new BufferedInputStream(inStream);ByteArrayOutputStream out = new ByteArrayOutputStream(1024);byte[] temp = new byte[1024];int size = 0;while ((size = in.read(temp)) != -1) {out.write(temp, 0, size);}in.close();ServletOutputStream os = response.getOutputStream();os.write(out.toByteArray());os.flush();os.close();flag = true;} catch (Exception e) {logger.error("违法信息下载...出错了");}return flag;}makeImage(); ⽅法(如果是服务器上的图⽚,可以省略这⼀步,直接打包)/*** 下载图⽚,并按照指定的路径存储* @param bean* @param filePath*/public void makeImage( String filePath) {// ⽹络请求所需变量try {//new⼀个URL对象URL url = new URL(filePath);//打开链接HttpURLConnection conn = (HttpURLConnection)url.openConnection();//设置请求⽅式为"GET"conn.setRequestMethod("GET");//超时响应时间为5秒conn.setConnectTimeout(5 * 1000);//通过输⼊流获取图⽚数据InputStream inStream = conn.getInputStream();ByteArrayOutputStream outStream = new ByteArrayOutputStream();//创建⼀个Buffer字符串byte[] buffer = new byte[1024];//每次读取的字符串长度,如果为-1,代表全部读取完毕int len = 0;//使⽤⼀个输⼊流从buffer⾥把数据读取出来while( (len=inStream.read(buffer)) != -1 ){//⽤输出流往buffer⾥写⼊数据,中间参数代表从哪个位置开始读,len代表读取的长度outStream.write(buffer, 0, len);}byte []data=outStream.toByteArray();//先将图⽚从url下载到服务器的D:/upload/File imageFile = new File("D:/upload/"+filePath.substring(stIndexOf("/")));//创建输出流FileOutputStream foutStream = new FileOutputStream(imageFile);foutStream.write(data);//关闭输出流foutStream.close();inStream.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JAVA中使⽤FTPClient实现⽂件上传下载实例代码在java程序开发中,ftp⽤的⽐较多,经常打交道,⽐如说向FTP服务器上传⽂件、下载⽂件,本⽂给⼤家介绍如何利⽤jakarta commons中的FTPClient(在commons-net包中)实现上传下载⽂件。
⼀、上传⽂件原理就不介绍了,⼤家直接看代码吧/*** Description: 向FTP服务器上传⽂件* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@)创建* @param url FTP服务器hostname* @param port FTP服务器端⼝* @param username FTP登录账号* @param password FTP登录密码* @param path FTP服务器保存⽬录* @param filename 上传到FTP服务器上的⽂件名* @param input 输⼊流* @return 成功返回true,否则返回false*/publicstaticboolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);//连接FTP服务器//如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(path);ftp.storeFile(filename, input);input.close();ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}<pre></pre>/*** Description: 向FTP服务器上传⽂件* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@)创建* @param url FTP服务器hostname* @param port FTP服务器端⼝* @param username FTP登录账号* @param password FTP登录密码* @param path FTP服务器保存⽬录* @param filename 上传到FTP服务器上的⽂件名* @param input 输⼊流* @return 成功返回true,否则返回false*/public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);//连接FTP服务器//如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(path);ftp.storeFile(filename, input);input.close();ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}下⾯我们写两个⼩例⼦:1.将本地⽂件上传到FTP服务器上,代码如下:@Testpublicvoid testUpLoadFromDisk(){try {FileInputStream in=new FileInputStream(new File("D:/test.txt"));boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", in); System.out.println(flag);} catch (FileNotFoundException e) {e.printStackTrace();}}<pre></pre>@Testpublic void testUpLoadFromDisk(){try {FileInputStream in=new FileInputStream(new File("D:/test.txt"));boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", in); System.out.println(flag);} catch (FileNotFoundException e) {e.printStackTrace();}}2.在FTP服务器上⽣成⼀个⽂件,并将⼀个字符串写⼊到该⽂件中@Testpublicvoid testUpLoadFromString(){try {InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", input); System.out.println(flag);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}<pre></pre>@Testpublic void testUpLoadFromString(){try {InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", input); System.out.println(flag);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}⼆、下载⽂件从FTP服务器下载⽂件的代码也很简单,参考如下:/*** Description: 从FTP服务器下载⽂件* @Version. Jul , :: PM by 崔红保(cuihongbao@)创建* @param url FTP服务器hostname* @param port FTP服务器端⼝* @param username FTP登录账号* @param password FTP登录密码* @param remotePath FTP服务器上的相对路径* @param fileName 要下载的⽂件名* @param localPath 下载后保存到本地的路径* @return*/publicstaticboolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) { boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);//如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器⽬录FTPFile[] fs = ftp.listFiles();for(FTPFile ff:fs){if(ff.getName().equals(fileName)){File localFile = new File(localPath+"/"+ff.getName());OutputStream is = new FileOutputStream(localFile);ftp.retrieveFile(ff.getName(), is);is.close();}}ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}<pre></pre>。
java实现⽂件上传和下载本⽂实例为⼤家分享了java实现⽂件上传和下载的具体代码,供⼤家参考,具体内容如下⽂件的上传upload:⽂件上传客户端通过表单的⽂件域file 把客户端的⽂件上传保存到服务器的硬盘上页⾯⾸先对上传的表单有以下要求:必须有⽂件域:input type=file表单提交⽅式:method=post表单的 enctype=multipart/form-data<form method="post" action="/user/regist" enctype="multipart/form-data"><table style="border: chartreuse;solid:2px"><tr><th>⽤户名</th><td><input type="text" name="username"></td></tr><tr><th>密码</th><td><input type="password" name="password"></td></tr><tr><th>⽤户头像</th><td><input type="file" name="photo"> </td></tr><tr><td colspan="2"><input type="submit" value="提交"></td></tr></table></form>Servlet1)⾸先要导⼊以下两个jar包,通过commons-fileupload实现⽂件上传2)创建⼀个⼯⼚对象DiskFileItemFactory,在创建⼀个多部件表单解析器ServletFileUpload,构造⽅法传⼊⼯⼚对象3)解析器解析请求对象,获得⼀个list集合,其中list集合存储的是⼀个⼀个的fileItem对象,⼀个fileItem对应⼀个组件,也就是⼀个<input>4) 遍历集合⽤isFormField()⽅法判断是否为普通组件,然后着重处理⽂件域组件5)获取⽂件名,并⽤getRealPath⽅法获取服务器上传⽂件所在路径,创建新⽂件夹6)获取输⼊流和创建输出流,进⾏⽂件的读写@WebServlet(value = "/user/regist")public class UploadServlet extends HttpServlet {protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//创建⼀个⼯⼚对象DiskFileItemFactory factory = new DiskFileItemFactory();//创建⼀个多部件解析器对象ServletFileUpload fileUpload = new ServletFileUpload(factory);User user = new User();FileOutputStream out=null;try {//⽤解析器对象解析请求,返回⼀个FileItem类型的集合List<FileItem> list = fileUpload.parseRequest(req);for (FileItem fileItem : list) {/*** fileItem.getFieldName());:::获取组件的name值* fileItem.getName());::::获取⽂件域的⽂件名* fileItem.getSize());::::获取数据的字节个数* fileItem.getString());::::获取数据的字符串* fileItem.isFormField());:::判断是否为普通组件*///判断部件是否为普通组件if (fileItem.isFormField()) {//普通组件//获取组件名字也就是name的值String fieldName = fileItem.getFieldName();//获取组件的值也就是value的值String value = fileItem.getString("utf-8");if ("username".equals(fieldName)) { //设置实体类的属性user.setUsername(value);} else if ("password".equals(fieldName)) {user.setPassword(value);}} else {// ⽂件域//获取⽂件名String fielName = fileItem.getName();//输⼊流来读数据InputStream in = fileItem.getInputStream();//设置⽂件写出的路径,并⽤随机码来保证图⽚可以重复String path=req.getServletContext().getRealPath("/imgs/"+ UUID.randomUUID()+fielName);System.out.println("⽂件路径为:"+path);File file = new File(path);out = new FileOutputStream(file);//利⽤commons-io-1.4.jar的IOUtils的copy⽅法直接实现⽂件的复制IOUtils.copy(in,out);user.setPhoto(file.getName());}}} catch (Exception e) {e.printStackTrace();}finally {if(out!=null){out.close();}}req.getSession().setAttribute("user",user);req.getRequestDispatcher("/sucess.jsp").forward(req,resp);}}⽂件的下载页⾯只需⼀个超链接,传需要下载的⽂件名,或者直接输⼊路径在浏览器例: <a href="<c:url value='/file/download?fileName=14.jpg'/>" >狗狗1</a><br/>Servlet1)接收参数,获取⽂件名2)获取imgs的路径,也就是存储⽂件的⽂件夹的路径,然后创建⽂件,传⼊该路径和⽂件名3)创建输⼊流读取⽂件4)设置响应头,⾸先根据⽂件名字获取⽂件的⼤类型,设置响应头Content-Type指定响应的类型;设置响应头Content-Disposition,指定⽂件以附件形式保存到本地磁盘5)⽤响应获取输出流,读出⽂件到客户端@WebServlet("/user/download")public class DownloadServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");//获取要下载的⽂件名String fileName = request.getParameter("fileName");System.out.println(fileName);//获取服务器中存储图⽚的⽂件夹的路径String path1 = request.getServletContext().getRealPath("/imgs");String path=path1+"/"+fileName;File file = new File(path);//创建输⼊流读⽂件FileInputStream in = new FileInputStream(file);//通过⽂件名字获取⽂件的⼤类型String type = request.getServletContext().getMimeType(fileName);//设置响应头ContentType指定响应内容的类型response.setHeader("Content-type",type);//设置响应头Content-Disposition 指定以附件形式保存响应的信息response.setHeader("Content-Disposition","attachment;filename="+(URLEncoder.encode(fileName, "utf-8"))); ServletOutputStream out = response.getOutputStream();//实现⽂件的读写IOUtils.copy(in,out);if(in!=null){in.close();}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
简单的文件下载,可以通过URL直接访问,主功能还是在servlet里实现比较好,在web.xml配置一下即可:package com.imeOM.action;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** 文件下载Servlet<br/>* request里面存储文件全路径.filepath=文件全路径,filename=文件名称* @author yjg**/public class FileDownload extends HttpServlet{/*** httpServletID号*/private static final long serialVersionUID = 101L;public void service(HttpServletRequest req,HttpServletResponse res) throws IOException{String filepath=req.getParameter("filepath");String filename=req.getParameter("filename");if(filepath!=null){File file=new File(filepath);if(!file.exists()){res.setContentType("text/html;charset=UTF-8");res.getWriter().print("指定文件不存在");return;}else{ServletOutputStream out=res.getOutputStream();res.setHeader("Content-disposition", "attachment;filename="+new String(filename.getBytes("utf-8"),"iso8859-1"));//重新编码,不然可能会出现乱码现象sres.addHeader("Content-Length", ""+file.length());BufferedInputStream bis=null;BufferedOutputStream bos=null;try{bis=new BufferedInputStream(new FileInputStream(filepath));bos=new BufferedOutputStream(out);byte[] buff=new byte[2048];int bytesRead;while(-1!=(bytesRead=bis.read(buff,0,buff.length))){bos.write(buff,0,bytesRead);}}catch(Exception e){e.printStackTrace();res.setContentType("text/html;charset=UTF-8");res.getWriter().print("文件已找到,下载失败");return;}finally{if(bis!=null)bis.close();if(bos!=null)bos.close();}}}}}web.xml配置<servlet><servlet-name>FileDownload</servlet-name><servlet-class>com.imeOM.action.FileDownload</servlet-class> </servlet><servlet-mapping><servlet-name>FileDownload</servlet-name><url-pattern>/fileDownload</url-pattern></servlet-mapping>最后输入fileDownload?filepath=文件路径&filename=文件名称来下载了。
java实现简单的文件下载
文件下载需要在WebRoot 下创建images文件夹并且放入test.txt文件创建jsp文件夹放入01.jsp
index.jsp 不变web.xml需要配置servlet 适合初学者研究学习
//index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
My JSP 'index.jsp' starting page [下载]
//jsp文件夹下的01.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
下载:test1.txt ${errorResult}
//文件下载serlvet
package com.kero99.ygc.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件下载路径
String path = getServletContext().getRealPath("/") + "images/";
String filename = req.getParameter("filename");
File file = new File(path + filename);
if(file.exists()){
//设置相应类型application/octet-stream
resp.setContentType("application/x-msdownload");
//设置头信息Content-Disposition为属性名附件形式打开下载文件指定名称为设定的filename
resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
//输入流写入输出流
InputStream inputStream = new FileInputStream(file);
ServletOutputStream ouputStream = resp.getOutputStream();
byte b[] = new byte[1024];
int n ;
//循环读取!=-1读取完毕
while((n = inputStream.read(b)) != -1){
//写入到输出流从0读取到n
ouputStream.write(b,0,n);
}
//关闭流、释放资源
ouputStream.close();
inputStream.close();
}else{
req.setAttribute("errorResult", "文件不存在下载失败!");
RequestDispatcher dispatcher = req.getRequestDispatcher("https:///qq_17025903/article/details/jsp/01.jsp");
dispatcher.forward(req, resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}
//web.xml
<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app id="WebApp_ID" version="2.5" xmlns="https:///xml/ns/javaee" xmlns:web="https:///xml/ns/javaee/web-app_2_5.xsd"
xmlns:xsi="https:///2001/XMLSchema-instance"
xsi:schemalocation="https:///xml/ns/javaee
https:///xml/ns/javaee/web-app_2_5.xsd">
<display-name>20170428_V1.0_download</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.kero99.ygc.download.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/downloadServlet.do</url-pattern>
</servlet-mapping>
</web-app>。