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=文件名称来下载了。
javaweb简单的实现⽂件下载及预览@ResponseBody@RequestMapping(value="/downloadFile")public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{//解决乱码问题String path = request.getParameter("path");String fileName = request.getParameter("fileName");path = MyUtils.isRandomCode(path);fileName = MyUtils.isRandomCode(fileName);try {String filePath = path+fileName;//⾼速浏览器以附件形式下载//不同浏览器的编码不同,对中⽂进⾏编码,下载时输出名称是⽂件名response.setHeader("Content-Disposition","attachment;filename="+fileName);//获取⽂件的mimetype,如123.txt,他的mimetype就是 txt ,下载时,就以 txt 格式下载String mimeType = fileName.substring(stIndexOf(".") + 1); //获取⽂件后缀,⽐如是 txt ⽂件,就是以txt格式下载//设置响应的 mimetyperesponse.setContentType(mimeType);//获取response 输出流,⽤来输出⽂件ServletOutputStream out = response.getOutputStream();//接下来进⾏读取,以输⼊流的形式读取FileInputStream in = new FileInputStream(filePath);byte[] buffer = new byte[1024];int len = 0;while ((len=in.read(buffer))!=-1){out.write(buffer,0,len);}in.close();} catch (Exception e) {System.out.println("下载错误!");}}这⾥有⼀个⼯具类,就是前端传过来的参数有可能会乱码,所以要判断⼀下是否乱码,有乱码的话就处理⼀下package com.zhouhe.modules.api.util;import java.io.UnsupportedEncodingException;/*** ⾃定义⼯具类* @Author zhouhe* @Date 2019/11/15 11:54*/public class MyUtils {/*** 判断是否是乱码,乱码的话进⾏处理,不乱码直接返回* @param code* @return*/public static String isRandomCode(String code) throws UnsupportedEncodingException {if (!XUtil.isEmpty(code)) {//判断是乱码 (GBK包含全部中⽂字符;UTF-8则包含全世界所有国家需要⽤到的字符。
Java中都通⽤⽂件下载(ContentType、⽂件头、response、out四步骤)我们就直接切⼊主题啦,⽂件下载只需要四步:1.设置⽂件ContentType类型2.设置⽂件头3.通过response获取ServletOutputStream对象(out)4.写到输出流(out)中下载代码:这⾥我使⽤的是SpringMVC,不过它在这⾥的唯⼀⽤途就是⽤来获取ServletContext对象,这个对象的⽤途,下⾯实例中有说明下载,需要⽤到两个jar包:commons-fileupload.jar和commons-io.jarJava代码1. import org.springframework.stereotype.Controller;2. import org.springframework.web.bind.annotation.RequestMapping;3. import org.springframework.web.context.ServletContextAware;4.5. import javax.servlet.ServletContext;6. import javax.servlet.ServletOutputStream;7. import javax.servlet.http.HttpServletResponse;8. import java.io.*;9.10. @Controller11. public class FileController implements ServletContextAware{12. //Spring这⾥是通过实现ServletContextAware接⼝来注⼊ServletContext对象13. private ServletContext servletContext;14.15.16. @RequestMapping("file/download")17. public void fileDownload(HttpServletResponse response){18. //获取⽹站部署路径(通过ServletContext对象),⽤于确定下载⽂件位置,从⽽实现下载19. String path = servletContext.getRealPath("/");20.21. //1.设置⽂件ContentType类型,这样设置,会⾃动判断下载⽂件类型22. response.setContentType("multipart/form-data");23. //2.设置⽂件头:最后⼀个参数是设置下载⽂件名(假如我们叫a.pdf)24. response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");25. ServletOutputStream out;26. //通过⽂件路径获得File对象(假如此路径中有⼀个download.pdf⽂件)27. File file = new File(path + "download/" + "download.pdf");28.29. try {30. FileInputStream inputStream = new FileInputStream(file);31.32. //3.通过response获取ServletOutputStream对象(out)33. out = response.getOutputStream();34.35. int b = 0;36. byte[] buffer = new byte[512];37. while (b != -1){38. b = inputStream.read(buffer);39. //4.写到输出流(out)中40. out.write(buffer,0,b);41. }42. inputStream.close();43. out.close();44. out.flush();45.46. } catch (IOException e) {47. e.printStackTrace();48. }49. }50.51. @Override52. public void setServletContext(ServletContext servletContext) {53. this.servletContext = servletContext;54. }55. }。
Java实现bt⽂件下载、制作、解析、磁⼒链接⾸先torrent⾥⾯肯定携带的有⼀些信息,所以就需要我们来解析这些信息。
我们这⾥做多⽂件制作torrent,所以⾸先要针对每⼀个⽂件建⼀个实体类[java]1. import java.util.List;2.3. public class Info {4. private String name;5. private byte[] pieces;6. private long piecesLength;7. private long length;8. private String md5sum;9. private List<Files> files;10.11. public Info() {12. }13.14. public Info(String name, byte[] pieces, long piecesLength, long length, String md5sum, List<Files> files) {15. super();16. = name;17. this.pieces = pieces;18. this.piecesLength = piecesLength;19. this.length = length;20. this.md5sum = md5sum;21. this.files = files;22. }23.24. public String getName() {25. return name;26. }27.28. public void setName(String name) {29. = name;30. }31.32. public byte[] getPieces() {33. return pieces;34. }35.36. public void setPieces(byte[] pieces) {37. this.pieces = pieces;38. }39.40. public long getPiecesLength() {41. return piecesLength;42. }43.44. public void setPiecesLength(long piecesLength) {45. this.piecesLength = piecesLength;46. }47.48. public long getLength() {49. return length;50. }51.52. public void setLength(long length) {53. this.length = length;54. }55.56. public String getMd5sum() {57. return md5sum;58. }59.60. public void setMd5sum(String md5sum) {61. this.md5sum = md5sum;62. }63.64. public List<Files> getFiles() {65. return files;66. }67.68. public void setFiles(List<Files> files) {69. this.files = files;70. }⽽对于每⼀个File,⼜存在了⼀些信息,所以我们针对File建⽴⼀个实体类[java]1. import java.util.List;2.3. public class Files {4. private long length;5. private String md5sum;6. private List<String> path;7.8. public Files() {9. }10. //getter and setter and tostring11.12. public long getLength() {13. return length;14. }15.16. public Files(long length, String md5sum, List<String> path) {17. super();18. this.length = length;19. this.md5sum = md5sum;20. this.path = path;21. }22.23. public void setLength(long length) {24. this.length = length;25. }26.27. public String getMd5sum() {28. return md5sum;29. }30.31. public void setMd5sum(String md5sum) {32. this.md5sum = md5sum;33. }34.35. public List<String> getPath() {36. return path;37. }38.39. public void setPath(List<String> path) {40. this.path = path;41. }42. }⽽我们在制作torrent⽂件时,填写了很多信息,⽐如要web seeds等等。
java实现连接sftp服务器并下载⽂件到本地1.pom.xml引⼊jar包<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version></dependency>2.连接sftp服务器⽅法private static Session sshSession;/*** 连接sftp服务器* @param host ftp地址* @param port 端⼝* @param userName 账号* @param password 密码* @return*/public static ChannelSftp sftpConnection(String host,int port, String userName, String password){JSch jsch = new JSch();ChannelSftp channelSftp;try {jsch.getSession(userName, host, port);sshSession = jsch.getSession(userName, host, port);sshSession.setPassword(password);Properties properties = new Properties();properties.put("StrictHostKeyChecking", "no");sshSession.setConfig(properties);sshSession.connect();Channel channel = sshSession.openChannel("sftp");channel.connect();channelSftp = (ChannelSftp) channel;}catch (JSchException e){e.printStackTrace();throw new RRException("Sftp服务器登录异常!");}return channelSftp;}3.断开sftp服务⽅法/***@description 退出Sftp服务器登录*@return**/public static void sftpClose(ChannelSftp channelSftp){if (channelSftp != null) {if (channelSftp.isConnected()){channelSftp.disconnect();}}}/*** 关闭session*/public static void sessionClose(){if (sshSession != null) {if (sshSession.isConnected()){sshSession.disconnect();sshSession = null;}}}4.下载sftp服务器知道路径的⽂件到本地⽅法/*** 下载sftp⽂件* @param sftp* @param newFileName 新⽂件名称* @param path ⽂件路径* @param fileName ⽂件名称* @param downUrl 下载到本地的路径* @throws Exception*/public static void downSftpFile(ChannelSftp sftp, String newFileName,String path, String fileName, String downUrl) throws Exception {OutputStream os=null;try {File localFile = new File(downUrl + "/" + newFileName);if (!localFile.getParentFile().exists()) {localFile.getParentFile().mkdirs();localFile.createNewFile();}if (path != null && !"".equals(path)) {sftp.cd(path);//进⼊所在路径}os = new FileOutputStream(localFile);sftp.get(path + fileName, os);os.close();}catch (Exception e){e.printStackTrace();}}。
java从服务器下载⽂件并保存到本地的⽰例昨天在做⼀个项⽬时,⽤到了从服务器上下载⽂件并保存到本地的知识,以前也没有接触过,昨天搞了⼀天,这个⼩功能实现了,下⾯就简单的说⼀下实现过程;1.基础知识当我们想要下载⽹站上的某个资源时,我们会获取⼀个url,它是服务器定位资源的⼀个描述,下载的过程有如下⼏步:(1)客户端发起⼀个url请求,获取连接对象。
(2)服务器解析url,并且将指定的资源返回⼀个输⼊流给客户。
(3)建⽴存储的⽬录以及保存的⽂件名。
(4)输出了写数据。
(5)关闭输⼊流和输出流。
2.实现代码的⽅法/*** @功能下载临时素材接⼝* @param filePath ⽂件将要保存的⽬录* @param method 请求⽅法,包括POST和GET* @param url 请求的路径* @return*/public static File saveUrlAs(String url,String filePath,String method){//System.out.println("fileName---->"+filePath);//创建不同的⽂件夹⽬录File file=new File(filePath);//判断⽂件夹是否存在if (!file.exists()){//如果⽂件夹不存在,则创建新的的⽂件夹file.mkdirs();}FileOutputStream fileOut = null;HttpURLConnection conn = null;InputStream inputStream = null;try{// 建⽴链接URL httpUrl=new URL(url);conn=(HttpURLConnection) httpUrl.openConnection();//以Post⽅式提交表单,默认get⽅式conn.setRequestMethod(method);conn.setDoInput(true);conn.setDoOutput(true);// post⽅式不能使⽤缓存conn.setUseCaches(false);//连接指定的资源conn.connect();//获取⽹络输⼊流inputStream=conn.getInputStream();BufferedInputStream bis = new BufferedInputStream(inputStream);//判断⽂件的保存路径后⾯是否以/结尾if (!filePath.endsWith("/")) {filePath += "/";}//写⼊到⽂件(注意⽂件保存路径的后⾯⼀定要加上⽂件的名称)fileOut = new FileOutputStream(filePath+"123.png");BufferedOutputStream bos = new BufferedOutputStream(fileOut);byte[] buf = new byte[4096];int length = bis.read(buf);//保存⽂件while(length != -1){bos.write(buf, 0, length);length = bis.read(buf);}bos.close();bis.close();conn.disconnect();} catch (Exception e){e.printStackTrace();System.out.println("抛出异常!!");}return file;}3.代码测试类(主函数)/*** @param args*/public static void main(String[] args){String photoUrl = "https:///5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"; String fileName = photoUrl.substring(stIndexOf("/"));//System.out.println("fileName---->"+fileName);String filePath = "d:";File file = saveUrlAs(photoUrl, filePath + fileName,"GET");System.out.println("Run ok!/n<BR>Get URL file " + file);}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Java后台Controller实现⽂件下载操作代码参数: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("成功");elseSystem.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(stIndexOf(".") + 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)){//转换成多部分requestMultipartHttpServletRequest 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实现⽂件下载操作就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
javaweb如何实现⽂件下载功能?⼀、超链接下载:这种⽅式⾮常简单,就是在超链接⾥⾯写上即将下载的⽂件路径,我这⾥将⽂件放在webapp下⾯的download⽂件夹⾥⾯:<a href="download/notice1.pdf"></a>但是有⼀个弊端就是,如果下载的⽂件可以直接被浏览器识别就会⾃动打开,⽐如.png,.pdf⽂件,如果是.zip等⽂件,则不会打开。
⼆、Servlet下载:为了解决第⼀种⽅式的弊端,我们采取Servlet下载⽅式。
1.新建Servlet⽂件,可以命名为DownloadServlet,映射url是“/downloadServlet”,我的项⽬名称是suiningAdmissions;2.在DownloadServlet中加⼊以下内容,其中filename是你在下载的时候需要传递的参数,是你即将下载的⽂件的名称;package cn.itIcey.suining.web.servlet;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;@WebServlet("/downloadServlet")public class DownloadServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获得请求⽂件名String filename = request.getParameter("filename");System.out.println(filename);//设置⽂件MIME类型response.setContentType(getServletContext().getMimeType(filename));//设置Content-Dispositionresponse.setHeader("Content-Disposition", "attachment;filename="+filename);//读取⽬标⽂件,通过response将⽬标⽂件写到客户端//获取⽬标⽂件的绝对路径String fullFileName = getServletContext().getRealPath("/download/" + filename);//System.out.println(fullFileName);//读取⽂件InputStream in = new FileInputStream(fullFileName);OutputStream out = response.getOutputStream();byte[] buffer = new byte[1024];int len;//循环取出流中的数据while((len = in.read(buffer)) != -1){out.write(buffer,0,len);}in.close();out.close();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}}3.将下载链接重新设置,其中/suiningAdmission/downloadServlet是我创建的Servlet的映射路径,注意⼀定要把前⾯的项⽬名称加上去!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>。