Jsp+Servlet实现文件上传下载 文件上传(一)
文件上传和下载功能是java web必备技能,很实用。
本文使用的是apache下的著名的文件上传组件
org.apache.commons.fileupload 实现
下面结合最近看到的一些资料以及自己的尝试,先写第一篇文件上传。后续会逐步实现下载,展示文件列表,上传信息持久化等。
废话少说,直接上代码
第一步、引用jar包,设置上传目录
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
上传目录:web-inf/tempfiles和web-inf/uploadfiles
第二步、编写jsp页面
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>文件上传测试</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="<%=request.getcontextpath()%>/uploadservlet">
文件: <input type="file" name="upfile"><br/>
<br/>
<input type="submit" value="上传">
</form>
<c:if test="${not empty errormessage}">
<input type="text" id="errormessage" value="${errormessage}" style="color:red;" disabled="disabled">
</c:if>
</body>
</html>
第三步、编写servlet,处理文件上传的核心
package servlet;
import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.fileuploadbase;
import org.apache.commons.fileupload.fileuploadexception;
import org.apache.commons.fileupload.progresslistener;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
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.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.util.calendar;
import java.util.iterator;
import java.util.list;
import java.util.uuid;
/**
* 处理文件上传
*
* @author xusucheng
* @create 2017-12-27
**/
@webservlet("/uploadservlet")
public class uploadservlet extends httpservlet {
@override
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
//设置文件上传基本路径
string savepath = this.getservletcontext().getrealpath("/web-inf/uploadfiles");
//设置临时文件路径
string temppath = this.getservletcontext().getrealpath("/web-inf/tempfiles");
file tempfile = new file(temppath);
if (!tempfile.exists()) {
tempfile.mkdir();
}
//定义异常消息
string errormessage = "";
//创建file items工厂
diskfileitemfactory factory = new diskfileitemfactory();
//设置缓冲区大小
factory.setsizethreshold(1024 * 100);
//设置临时文件路径
factory.setrepository(tempfile);
//创建文件上传处理器
servletfileupload upload = new servletfileupload(factory);
//监听文件上传进度
progresslistener progresslistener = new progresslistener() {
public void update(long pbytesread, long pcontentlength, int pitems) {
system.out.println("正在读取文件: " + pitems);
if (pcontentlength == -1) {
system.out.println("已读取: " + pbytesread + " 剩余0");
} else {
system.out.println("文件总大小:" + pcontentlength + " 已读取:" + pbytesread);
}
}
};
upload.setprogresslistener(progresslistener);
//解决上传文件名的中文乱码
upload.setheaderencoding("utf-8");
//判断提交上来的数据是否是上传表单的数据
if (!servletfileupload.ismultipartcontent(request)) {
//按照传统方式获取数据
return;
}
//设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1mb
upload.setfilesizemax(1024 * 1024);
//设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10mb
upload.setsizemax(1024 * 1024 * 10);
try {
//使用servletfileupload解析器解析上传数据,解析结果返回的是一个list<fileitem>集合,每一个fileitem对应一个form表单的输入项
list<fileitem> items = upload.parserequest(request);
iterator<fileitem> iterator = items.iterator();
while (iterator.hasnext()) {
fileitem item = iterator.next();
//判断jsp提交过来的是不是文件
if (item.isformfield()) {
errormessage = "请提交文件!";
break;
} else {
//文件名
string filename = item.getname();
if (filename == null || filename.trim() == "") {
system.out.println("文件名为空!");
}
//处理不同浏览器提交的文件名带路径问题
filename = filename.substring(filename.lastindexof("\\") + 1);
//文件扩展名
string fileextension = filename.substring(filename.lastindexof(".") + 1);
//判断扩展名是否合法
if (!validextension(fileextension)) {
errormessage = "上传文件非法!";
item.delete();
break;
}
//获得文件输入流
inputstream in = item.getinputstream();
//得到保存文件的名称
string savefilename = createfilename(filename);
//得到文件保存路径
string realfilepath = createrealfilepath(savepath, savefilename);
//创建文件输出流
fileoutputstream out = new fileoutputstream(realfilepath);
//创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
//写文件
out.write(buffer, 0, len);
}
//关闭输入流
in.close();
//关闭输出流
out.close();
//删除临时文件 todo
item.delete();
//将上传文件信息保存到附件表中 todo
}
}
} catch (fileuploadbase.filesizelimitexceededexception e) {
e.printstacktrace();
request.setattribute("errormessage", "单个文件超出最大值!!!");
request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response);
return;
} catch (fileuploadbase.sizelimitexceededexception e) {
e.printstacktrace();
request.setattribute("errormessage", "上传文件的总的大小超出限制的最大值!!!");
request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response);
return;
} catch (fileuploadexception e) {
e.printstacktrace();
request.setattribute("errormessage", "文件上传失败!!!");
request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response);
return;
}
request.setattribute("errormessage", errormessage);
request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response);
}
@override
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
doget(request, response);
}
private boolean validextension(string fileextension) {
string[] exts = {"jpg", "txt", "doc", "pdf"};
for (int i = 0; i < exts.length; i++) {
if (fileextension.equals(exts[i])) {
return true;
}
}
return false;
}
private string createfilename(string filename) {
return uuid.randomuuid().tostring() + "_" + filename;
}
/**
* 根据基本路径和文件名称生成真实文件路径,基本路径\\年\\月\\filename
*
* @param basepath
* @param filename
* @return
*/
private string createrealfilepath(string basepath, string filename) {
calendar today = calendar.getinstance();
string year = string.valueof(today.get(calendar.year));
string month = string.valueof(today.get(calendar.month) + 1);
string uppath = basepath + file.separator + year + file.separator + month + file.separator;
file uploadfolder = new file(uppath);
if (!uploadfolder.exists()) {
uploadfolder.mkdirs();
}
string realfilepath = uppath + filename;
return realfilepath;
}
}
第四步、测试
http://localhost:8080/helloweb/pages/upload/upload.jsp


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。
相关文章
- 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页面的静态包含和动态包含使用方法


