Javaweb实现上传下载文件的多种方法
程序员文章站
2024-03-11 23:52:08
在javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传...
在javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为commons-fileupload依赖于commons-io这个包,所以需要下载这两个包commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。
1、搭建环境
创建web项目,将包导入到项目lib下
2、实现文件上传
(第一种上传的方法)
新建upload.jsp页面
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>upload file</title> </head> <body> <!--这里的<%=request.getcontextpath()%>是表示项目的绝对路径,也就是说不管你以后将项目拷贝到哪个位置,它都会找到准确的路径 --> <form action="<%=request.getcontextpath()%>/uploadservlet" enctype="multipart/form-data" method="post"> <span>选择文件:</span><input type="file" name="file1"> <input type="submit" value="上传"> </form> </body> </html>
新建处理文件上传的servlet
package com.load; import java.io.file; import java.io.ioexception; import java.util.list; import javax.servlet.servletcontext; 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 org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; @webservlet("/uploadservlet") public class uploadservlet extends httpservlet { private static final long serialversionuid = 1l; public uploadservlet() { super(); } /* fileupload 包中, http 请求中的复杂表单元素都被看做一个 fileitem 对象; * fileitem 对象必须由 servletfileupload 类中的 parserequest() 方法解析 http 请求 * (即被包装之后的 httpservletrequest 对象)出来,即分离出具体的文本表单和上传文件 * */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //通过ismultipartcontent()方法:分析请求里面是不是有文件上的请求, boolean ismultipart = servletfileupload.ismultipartcontent(request); if(ismultipart){ //创建可设置的磁盘节点工厂 diskfileitemfactory factory = new diskfileitemfactory(); //获取请求的上下文信息 servletcontext servletcontext = request.getservletcontext(); //缓存目录,每个服务器特定的目录 file repository = (file) servletcontext.getattribute("javax.servlet.context.tempdir"); //设置服务器的缓存目录 factory.setrepository(repository); //servletfileupload 对象的创建需要依赖于 fileitemfactory //工厂将获得的上传文件 fileitem 对象保存至服务器硬盘,即 diskfileitem 对象。 servletfileupload upload = new servletfileupload(factory); try { //解析即被包装之后的 httpservletrequest对象,既是分离文本表单和上传文件(http请求会被包装为httpservletrequest) list<fileitem> items = upload.parserequest(request); for(fileitem item:items){ string fieldname = item.getfieldname(); string filename = item.getname(); string contenttype = item.getcontenttype(); boolean isinmemory = item.isinmemory(); long sizeinbytes = item.getsize(); //实例化一个文件 //request.getrealpath(获取真实路径) file file = new file(request.getrealpath("/")+"/loads"+filename.substring(filename.lastindexof("\\")+1,filename.length())); item.write(file); } } catch (fileuploadexception e) { e.printstacktrace(); } catch (exception e) { e.printstacktrace(); } } } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } }
(第二种上传的方法)
新建jsp页面(同上,只是路径改变下)
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>upload file</title> </head> <body> <!--这里的<%=request.getcontextpath()%>是表示项目的绝对路径,也就是说不管你以后将项目拷贝到哪个位置,它都会找到准确的路径 --> <form action="<%=request.getcontextpath()%>/uploadservlet1" enctype="multipart/form-data" method="post"> <span>选择文件:</span><input type="file" name="file1"> <input type="submit" value="上传"> </form> </body> </html>
建立servlet处理上传
package com.load; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import javax.servlet.servletexception; import javax.servlet.annotation.multipartconfig; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.part; @webservlet("/uploadservlet1") @multipartconfig(location="") public class uploadservlet1 extends httpservlet { private static final long serialversionuid = 1l; public uploadservlet1() { super(); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); request.setcharacterencoding("utf-8"); //取得上传文件,读取文件 part part = request.getpart("file1"); //定义一个变量去接收文件名 string filename = null; //content-disposition: 就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名 //content-disposition:告诉浏览器以下载的方式打开文件 for (string content : part.getheader("content-disposition").split(";")) { system.out.println(content); //取得文件名 if (content.trim().startswith("filename")) { //截取文件名 filename = content.substring( content.indexof('=') + 1).trim().replace("\"", ""); } } //输出流 outputstream out = null; //输入流 inputstream filecontent = null; //file.separator 取得系统的分割线等数据 out = new fileoutputstream(new file("e:/loads" + file.separator + filename)); int read; //获得一个输入流 filecontent = part.getinputstream(); final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } system.out.println("new file " + filename + " created at " + "/loads"); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } }
(第三种上传的方法)
这里使用的是jspsmartupload包上传下载,笔者认为这种上传下载较为简单,但是好像不是很多人用,不懂。
创建html页面
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>上传文件</title> </head> <body> <p> </p> <p align="center">上传文件选择</p> <form method="post" action="../douploadservlet" enctype="multipart/form-data"> <table width="75%" border="1" align="center"> <tr><td><div align="center"> 1.<input type="file" name="file1" > </div></td></tr> <tr><td><div align="center"> 2.<input type="file" name="file2" > </div></td></tr> <tr><td><div align="center"> 3.<input type="file" name="file3" > </div></td></tr> <tr><td><div align="center"> <input type="submit" name="submit" value="上传他"> </div></td></tr> </table> </form> </body> </html>
创建servlet处理上传文件
package com.load; import java.io.ioexception; import java.io.printwriter; 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 javax.servlet.jsp.jspfactory; import javax.servlet.jsp.pagecontext; import com.jspsmart.upload.file; import com.jspsmart.upload.smartupload; import com.jspsmart.upload.smartuploadexception; @webservlet("/douploadservlet") public class douploadservlet extends httpservlet { private static final long serialversionuid = 1l; public douploadservlet() { super(); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); printwriter out = response.getwriter(); //新建一个智能上传对象 smartupload su = new smartupload(); /* * pagecontext pagecontext; httpsession session; servletcontext application; servletconfig config; jspwriter out; object page = this; httpservletrequest request, httpservletresponse response 其中page对象,request和response已经完成了实例化,而其它5个没有实例化的对象通过下面的方式实例化 pagecontext = jspxfactory.getpagecontext(this, request, response,null, true, 8192, true); */ //通过jsp工厂类获取上下文环境 pagecontext pagecontext = jspfactory.getdefaultfactory().getpagecontext(this, request, response, null, true, 8192, true); //上传初始化 su.initialize(pagecontext); //上传文件 try { su.upload(); //将上传文件保存到指定目录 int count = su.save("/share"); out.println(count+"个文件上传成功!<br>"+su.tostring()); } catch (smartuploadexception e) { e.printstacktrace(); } //逐个提取上传文件信息 for(int i=0;i<su.getfiles().getcount();i++){ file file = su.getfiles().getfile(i); //如果文件不存在 if(file.ismissing()) continue; //显示当前文件信息 out.println("<table border=1>"); out.println("<tr><td>表单项名(fieldname)</td></td>"+file.getfieldname()+"</td></tr>"); out.println("<tr><td>文件长度</td><td>"+file.getsize()+"</td></tr>"); out.println("<tr><td>文件名</td><td>"+file.getfilename()+"</td></tr>"); out.println("<tr><td>文件扩展名</td><td>"+file.getfileext()+"</td></tr>"); out.println("<tr><td>文件全名</td><td>"+file.getfilepathname()+"</td></tr>"); out.println("</table><br>"); } } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } }
注意:代码 int count = su.save("/share");表示你需要先建个文件夹,所以你可以先在webcontent建立一个,然后将项目取消部署,再重新部署进去之后就会在运行那边建立起一个文件夹了!
或者你可以直接找到运行的路径,然后建立share文件夹。
3、实现文件下载
(第一种文件下载)
注意:该代码是直接访问servlet类的
package com.load; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; //直接使用http://localhost:8080/test1/download进行下载,但是这个有缺陷,如果下载文件名中有中文,就会变成乱码现象! @webservlet("/download") public class download extends httpservlet { private static final long serialversionuid = 1l; public download() { super(); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/plain;charset=utf-8"); response.setcharacterencoding("utf-8"); response.setheader("location","中文.txt"); response.setheader("content-disposition", "attachment; filename=" + "账号.txt"); outputstream outputstream = response.getoutputstream(); inputstream inputstream = new fileinputstream("e:/loads"+"/账号.txt"); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputstream.read(buffer)) != -1) { outputstream.write(buffer, 0, i); } outputstream.flush(); outputstream.close(); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } }
(第二种下载方法)
新建jsp页面选择下载
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>下载</title> </head> <body> <a href="../dodownloadservlet?filename=呵呵.txt">点击下载</a> </body> </html>
创建servlet类进行下载(注意:该下载如果文件名是中文的话,一样会出现乱码现象)
package com.load; import java.io.bufferedinputstream; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.urlencoder; 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 javax.servlet.jsp.jspfactory; import javax.servlet.jsp.pagecontext; import org.hsqldb.lib.stringutil; import com.jspsmart.upload.smartupload; import com.jspsmart.upload.smartuploadexception; @webservlet("/dodownloadservlet") public class dodownloadservlet extends httpservlet { private static final long serialversionuid = 1l; public dodownloadservlet() { super(); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //得到下载文件的名称 //string filename = request.getparameter("filename"); //string filename = new string(filename.getbytes("iso8859-1"),"utf-8"); //新建smartupload对象 smartupload su = new smartupload(); pagecontext pagecontext = jspfactory.getdefaultfactory().getpagecontext(this, request, response, null, true, 8192, true); //上传初始化 su.initialize(pagecontext); //设置禁止打开该文件 su.setcontentdisposition(null); //下载文件 try { su.downloadfile("/listener/"+filename); } catch (smartuploadexception e) { // todo auto-generated catch block e.printstacktrace(); } } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } }
(第三种下载的方法)
同上的jsp页面代码,这里就不再重复了。
新建serlvet类,实现下载功能(注意:这里文件名就算是中文名,也不会出现乱码问题了!)
package com.load; import java.io.bufferedinputstream; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.urlencoder; 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 javax.servlet.jsp.jspfactory; import javax.servlet.jsp.pagecontext; import org.hsqldb.lib.stringutil; import com.jspsmart.upload.smartupload; import com.jspsmart.upload.smartuploadexception; @webservlet("/dodownloadservlet") public class dodownloadservlet extends httpservlet { private static final long serialversionuid = 1l; public dodownloadservlet() { super(); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //获得文件名称 string path1 = request.getparameter("filename"); //获得路径名称 string path = request.getsession().getservletcontext().getrealpath("/listener/"+path1); // path是根据日志路径和文件名拼接出来的 file file = new file(path); string filename = file.getname(); try { //判断是否是ie11 boolean flag= request.getheader("user-agent").indexof("like gecko")>0; //ie11 user-agent字符串:mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko //ie6~ie10版本的user-agent字符串:mozilla/5.0 (compatible; msie 10.0; windows nt 6.0; trident/6.0) if (request.getheader("user-agent").tolowercase().indexof("msie") >0||flag){ filename = urlencoder.encode(filename, "utf-8");//ie浏览器 }else { //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码, //这个文件名称用于浏览器的下载框中自动显示的文件名 filename = new string(filename.replaceall(" ", "").getbytes("utf-8"), "iso8859-1"); //firefox浏览器 //firefox浏览器user-agent字符串: //mozilla/5.0 (windows nt 6.1; wow64; rv:36.0) gecko/20100101 firefox/36.0 } inputstream fis = new bufferedinputstream(new fileinputstream(path)); byte[] buffer; buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addheader("content-disposition", "attachment;filename=" +filename); response.addheader("content-length", "" + file.length()); outputstream os = response.getoutputstream(); response.setcontenttype("application/octet-stream"); os.write(buffer);// 输出文件 os.flush(); os.close(); } catch (ioexception e) { e.printstacktrace(); } system.out.println(filename); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。