JavaServlet的文件上传和下载实现方法
程序员文章站
2022-04-29 16:43:37
先分析一下上传文件的流程
1-先通过前段页面中的选择文件选择要上传的图片
index.jsp
<%@ page language="java" impo...
先分析一下上传文件的流程
1-先通过前段页面中的选择文件选择要上传的图片
index.jsp
<%@ page language="java" import="java.util.*" pageencoding="utf-8" contenttype="text/html; charset=utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>my jsp 'index.jsp' starting page</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/common.js"></script> <script type="text/javascript" src="js/ajaxfileupload.js"></script> </head> <body> <input type="file" value="上传" name="inputimage" id="inputimage"> <input type="button" value="上传" id="upload"> <a id="download">下载</a> </body> </html>
2-点击提交按钮,通过ajax的文件上传访问服务器端
common.js
var path = (function() { //获取当前网址 var curwwwpath = window.document.location.href; //获取主机地址之后的目录 var pathname = window.document.location.pathname; var pos = curwwwpath.indexof(pathname); //获取主机地址 var localhostpath = curwwwpath.substring(0, pos); //获取带"/"的项目名 var projectname = pathname.substring(0, pathname.substr(1).indexof('/') + 1); return { curwwwpath: curwwwpath, pathname: pathname, localhostpath: localhostpath, projectname: projectname, //部署路径 deploypath: localhostpath + projectname }; })();
// 文件下载 $("a[id=download]").click(function(){ window.location.href=path.deploypath+"/filedown"; }); // 文件上传 $("input[id=upload]").click(function() { $.ajaxfileupload( { url : path.deploypath + "/fileup", // 处理页面的绝对路径 fileelementid : "inputimage", //file空间的id属性 datatype : "json", success : function(data) { alert("上传成功"); } }); });
3-服务器端响应保存或者下载
保存上传文件的fileupload.java
import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.arraylist; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import net.sf.json.jsonarray; 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; import com.stu.util.httputil; /** * 文件名称: com.stu.fileupload.fileupload.java<br/> * 初始作者: administrator<br/> * 创建日期: 2018-1-31<br/> * 功能说明: 文件上传 <br/> * =================================================<br/> * 修改记录:<br/> * 修改作者 日期 修改内容<br/> * ================================================<br/> * copyright (c) 2010-2011 .all rights reserved.<br/> */ public class fileupload extends httpservlet { private static final long serialversionuid = 1l; @override protected void service(httpservletrequest req, httpservletresponse res) throws servletexception, ioexception { // 获取到当前服务器所在的路径 string serverpath = req.getsession().getservletcontext().getrealpath("/"); // 设置保存上传文件的路径 string savedirpath = serverpath + "img"; file savedirpathfileobj = new file(savedirpath); // 如果当用来存放文件的目录不存在时,要创建该目录 if (!savedirpathfileobj.exists()) { savedirpathfileobj.mkdirs(); } // 创建一个解析器工厂 diskfileitemfactory factory = new diskfileitemfactory(); // 设置工厂的缓存区大小 factory.setsizethreshold(5 * 1024); // 文件上传的解析器(文件上传对象) servletfileupload upload = new servletfileupload(factory); // 设置上传文件的最大值 upload.setsizemax(3 * 1024 * 1024); // 设置编码格式 upload.setheaderencoding("utf-8"); try { // 上传以后的文件名 list<string> uploadfilenames = new arraylist<string>(); list<fileitem> fileitems = upload.parserequest(req); system.out.println(fileitems); for (fileitem file : fileitems) { // 新的文件名 string savefilename = uuid.randomuuid().tostring().replace("-", ""); // 文件的后缀 string oldfilename = new string(file.getname().getbytes(), "utf-8"); system.out.println("oldfilename" + oldfilename); string filetype = oldfilename.substring(oldfilename.lastindexof(".")); // 新的文件路径 string savefilepath = savedirpath + file.separator + savefilename + filetype; uploadfilenames.add(savefilename + filetype); // 保存上传的文件 file.write(new file(savefilepath)); } system.out.println(uploadfilenames); httputil.setattribute(req, "urls", uploadfilenames); res.setcontenttype("application/json;charset=utf-8"); printwriter pw = res.getwriter(); pw.print(jsonarray.fromobject(uploadfilenames)); } catch (fileuploadexception e) { e.printstacktrace(); } catch (exception e) { e.printstacktrace(); } } }
下载文件的filedownload.java
import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.arraylist; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import net.sf.json.jsonarray; 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; import com.stu.util.httputil; /** * 文件名称: com.stu.fileupload.fileupload.java<br/> * 初始作者: administrator<br/> * 创建日期: 2018-1-31<br/> * 功能说明: 文件上传 <br/> * =================================================<br/> * 修改记录:<br/> * 修改作者 日期 修改内容<br/> * ================================================<br/> * copyright (c) 2010-2011 .all rights reserved.<br/> */ public class fileupload extends httpservlet { private static final long serialversionuid = 1l; @override protected void service(httpservletrequest req, httpservletresponse res) throws servletexception, ioexception { // 获取到当前服务器所在的路径 string serverpath = req.getsession().getservletcontext().getrealpath("/"); // 设置保存上传文件的路径 string savedirpath = serverpath + "img"; file savedirpathfileobj = new file(savedirpath); // 如果当用来存放文件的目录不存在时,要创建该目录 if (!savedirpathfileobj.exists()) { savedirpathfileobj.mkdirs(); } // 创建一个解析器工厂 diskfileitemfactory factory = new diskfileitemfactory(); // 设置工厂的缓存区大小 factory.setsizethreshold(5 * 1024); // 文件上传的解析器(文件上传对象) servletfileupload upload = new servletfileupload(factory); // 设置上传文件的最大值 upload.setsizemax(3 * 1024 * 1024); // 设置编码格式 upload.setheaderencoding("utf-8"); try { // 上传以后的文件名 list<string> uploadfilenames = new arraylist<string>(); list<fileitem> fileitems = upload.parserequest(req); system.out.println(fileitems); for (fileitem file : fileitems) { // 新的文件名 string savefilename = uuid.randomuuid().tostring().replace("-", ""); // 文件的后缀 string oldfilename = new string(file.getname().getbytes(), "utf-8"); system.out.println("oldfilename" + oldfilename); string filetype = oldfilename.substring(oldfilename.lastindexof(".")); // 新的文件路径 string savefilepath = savedirpath + file.separator + savefilename + filetype; uploadfilenames.add(savefilename + filetype); // 保存上传的文件 file.write(new file(savefilepath)); } system.out.println(uploadfilenames); httputil.setattribute(req, "urls", uploadfilenames); res.setcontenttype("application/json;charset=utf-8"); printwriter pw = res.getwriter(); pw.print(jsonarray.fromobject(uploadfilenames)); } catch (fileuploadexception e) { e.printstacktrace(); } catch (exception e) { e.printstacktrace(); } } }
这里面用到了一个httputil类,代码如下:
import javax.servlet.filterconfig; import javax.servlet.servletconfig; import javax.servlet.servletcontext; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpsession; /** * 文件名称_com.niit.model2.util.httputil.java</br> * 初始作逯ܿadministrator</br> * 创建日期_2018-1-23</br> * 功能说明_这里用一句话描述这个类的作用--此句话需删除 <br/> * =================================================<br/> * 修改记录_br/> * 修改作迠日期 修改内容<br/> * ================================================<br/> * copyright (c) 2010-2011 .all rights reserved.<br/> */ public class httputil { private httputil() { } /** * 方法描述: [用于向不同的作用域存放属性]</br> * 初始作迺 administrator<br/> * 创建日期: 2018-1-23-上午11:24:45<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改记录_br/> * 修改作迠日期 修改内容<br/> * ================================================<br/> * void */ public static void setattribute(object scopeobj, string name, object value) { if (scopeobj instanceof httpservletrequest) { ((httpservletrequest) scopeobj).setattribute(name, value); } if (scopeobj instanceof httpsession) { ((httpsession) scopeobj).setattribute(name, value); } if (scopeobj instanceof servletcontext) { ((servletcontext) scopeobj).setattribute(name, value); } } /** * 方法描述: [获取作用域中指定名称的属性思</br> * 初始作迺 administrator<br/> * 创建日期: 2018-1-23-上午11:29:17<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改记录_br/> * 修改作迠日期 修改内容<br/> * ================================================<br/> * * @param scopeobj * @param name * @return * object */ public static object getattribute(object scopeobj, string name) { if (scopeobj instanceof httpservletrequest) { return ((httpservletrequest) scopeobj).getattribute(name); } if (scopeobj instanceof httpsession) { return ((httpsession) scopeobj).getattribute(name); } if (scopeobj instanceof servletcontext) { return ((servletcontext) scopeobj).getattribute(name); } return null; } /** * 方法描述: [获取上下文对象的方法]</br> * 初始作迺 administrator<br/> * 创建日期: 2018-1-23-上午11:31:26<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改记录_br/> * 修改作迠日期 修改内容<br/> * ================================================<br/> * * @return * servletcontext */ public static servletcontext getservletcontext(object sourceobj) { if (sourceobj instanceof httpservletrequest) { return ((httpservletrequest) sourceobj).getsession().getservletcontext(); } if (sourceobj instanceof servletconfig) { return ((servletconfig) sourceobj).getservletcontext(); } if (sourceobj instanceof filterconfig) { return ((filterconfig) sourceobj).getservletcontext(); } return null; } /** * 方法描述: [获取项目的实际路径]</br> * 初始作迺 administrator<br/> * 创建日期: 2018-1-23-上午11:45:47<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改记录_br/> * 修改作迠日期 修改内容<br/> * ================================================<br/> * * @param req * @return * string */ public static string getcontextpath(httpservletrequest req) { return req.getcontextpath(); } }
当然,代码编辑好了也不要忘了在 webroot/web-inf/web.xml 中添加新建的servlet,就是刚刚的两个java文件啦
<?xml version="1.0" encoding="utf-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 文件上传 --> <servlet> <servlet-name>fileupload</servlet-name> <servlet-class>com.stu.fileupload.fileupload</servlet-class> </servlet> <servlet-mapping> <servlet-name>fileupload</servlet-name> <url-pattern>/fileup</url-pattern> </servlet-mapping> <!-- 文件下载 --> <servlet> <servlet-name>filedownload</servlet-name> <servlet-class>com.stu.fileupload.filedownload</servlet-class> </servlet> <servlet-mapping> <servlet-name>filedownload</servlet-name> <url-pattern>/filedown</url-pattern> </servlet-mapping> </web-app>
这样的话就可以运行啦。
tip: 不要忘记相关的jar包和 js 包哦
在 webroot / web-inf / lib 下,有 commons-fileupload.jar 和 commons-io.jar ,另外 json-lib-x.x.x-jdkxx.jar 包是用来把上传的返回数据修改为json格式的
在 webroot / js 下,导入 jquery.js , common.js , ajaxfileupload.js
以上这篇javaservlet的文件上传和下载实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: 时间的判断问题
下一篇: laravel5.0升级到5.1