JavaServlet的文件上传和下载实现方法
先分析一下上传文件的流程
1-先通过前段页面中的选择文件选择要上传的图片
index.jsp
<%@ page language="java" import="java.util.*" pageencoding="utf-8"
contenttype="text/html; charset=utf-8"%>
my jsp 'index.jsp' starting page
下载 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
* 初始作者: administrator
* 创建日期: 2018-1-31
* 功能说明: 文件上传
* =================================================
* 修改记录:
* 修改作者 日期 修改内容
* ================================================
* copyright (c) 2010-2011 .all rights reserved.
*/
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 uploadfilenames = new arraylist();
list 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
* 初始作者: administrator
* 创建日期: 2018-1-31
* 功能说明: 文件上传
* =================================================
* 修改记录:
* 修改作者 日期 修改内容
* ================================================
* copyright (c) 2010-2011 .all rights reserved.
*/
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 uploadfilenames = new arraylist();
list 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
* 初始作逯ܿadministrator
* 创建日期_2018-1-23
* 功能说明_这里用一句话描述这个类的作用--此句话需删除
* =================================================
* 修改记录_br/>
* 修改作迠日期 修改内容
* ================================================
* copyright (c) 2010-2011 .all rights reserved.
*/
public class httputil {
private httputil() {
}
/**
* 方法描述: [用于向不同的作用域存放属性]
* 初始作迺 administrator
* 创建日期: 2018-1-23-上午11:24:45
* 弿Nj版本: 2.0.0
* =================================================
* 修改记录_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);
}
}
/**
* 方法描述: [获取作用域中指定名称的属性思
* 初始作迺 administrator
* 创建日期: 2018-1-23-上午11:29:17
* 弿Nj版本: 2.0.0
* =================================================
* 修改记录_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;
}
/**
* 方法描述: [获取上下文对象的方法]
* 初始作迺 administrator
* 创建日期: 2018-1-23-上午11:31:26
* 弿Nj版本: 2.0.0
* =================================================
* 修改记录_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;
}
/**
* 方法描述: [获取项目的实际路径]
* 初始作迺 administrator
* 创建日期: 2018-1-23-上午11:45:47
* 弿Nj版本: 2.0.0
* =================================================
* 修改记录_br/>
* 修改作迠日期 修改内容
* ================================================
*
* @param req
* @return
* string
*/
public static string getcontextpath(httpservletrequest req) {
return req.getcontextpath();
}
} 当然,代码编辑好了也不要忘了在 webroot/web-inf/web.xml 中添加新建的servlet,就是刚刚的两个java文件啦
index.jsp
fileupload com.stu.fileupload.fileupload fileupload /fileup
filedownload com.stu.fileupload.filedownload filedownload /filedown 这样的话就可以运行啦。
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
相关文章
- jsp+servlet实现文件上传与下载功能
- EJB3.0部署消息驱动Bean抛javax.naming.NameNotFoundException异常
- 在JSP中使用formatNumber控制要显示的小数位数方法
- 秒杀系统Web层设计的实现方法
- 将properties文件的配置设置为整个Web应用的全局变量实现方法
- JSP使用过滤器防止Xss漏洞
- 在JSP页面中动态生成图片验证码的方法实例
- 详解JSP 内置对象request常见用法
- 使用IDEA编写jsp时EL表达式不起作用的问题及解决方法
- jsp实现局部刷新页面、异步加载页面的方法
- Jsp中request的3个基础实践
- JavaServlet的文件上传和下载实现方法
- JSP页面的静态包含和动态包含使用方法


