刚刚发表了一篇Java发送电子邮件,以前真是没注意,commons里这么多常用项目,惭愧呀,直到现在回顾;要学习的真是太多了,还是缺少真正的学习能力...
这里用到的是commons-fileupload.jar与commons-io.jar;下载地址http://commons.apache.org/
这是一个web工程,所以先在webroot下新建一个jsp,其实直接用index.jsp就行了;下面是前端代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
</head>
<body>
<c:if test="${param.code=='001' }">操作成功</c:if>
<form action="file.jspx" method="post" enctype="multipart/form-data">
文件描述:<input type="text" name="describe"/><br/>
文件位置<input type="file" name="file"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
这里表单请求到的是一个servlet,在src中创建一个Servlet,此处取名FileUpLoadServlet.java
代码实现如下:
package com.wf.web;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
File file=new File("D:/upload");//上传文件保存位置
File tempfile=new File("D:/tempload");//上传缓存临时文件夹
if(!file.exists()){
file.mkdir();
}
if(!tempfile.exists()){
tempfile.mkdir();
}
//判断是否上传文件表单,也就是form中是否有enctype="multipart/form-data"项;必须post提交,get提交对内容长度有限制
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold(1024*512);//设置缓冲区大小
factory.setRepository(tempfile);//设置临时文件夹
ServletFileUpload fileUpload=new ServletFileUpload(factory);
fileUpload.setFileSizeMax(10*1024*1024);//设置最大文件大小
try {
@SuppressWarnings("unchecked")
List<FileItem> items=fileUpload.parseRequest(request);//获取所有表单
for(FileItem item:items){
//判断当前的表单控件是否是一个普通控件
if(!item.isFormField()){
//是一个文件控件时
String name=item.getName();
System.out.println("上传文件名:"+name);
System.out.println("文件大小:"+item.getSize());
String extName=name.substring(name.lastIndexOf("."));
String newName=new SimpleDateFormat("yyyyMMDDHHmmssms").format(new Date());
System.out.println("扩展名"+extName);
item.write(new File("d:/upload/"+newName+extName));
}else{
//是普通控件时
String desc=item.getString("UTF-8");
System.out.println("文件描述"+desc);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
throw new RuntimeException("请设置form表单的enctype属性");
}
response.sendRedirect("index.jsp?code=001");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
这里对上传文件的名字做了改变,防止上传同名文件(若同名,后覆盖前);
还有一点要注意,要是把这些上传文件放到WebRoot跟目录下,file的路径就不能为"D:/upload"了
通过
String webRootPath = getServletContext().getRealPath("/");
System.out.println("webRootPath:" + webRootPath);
File file = new File(webRootPath+"upload");
获取webroot,最后将item.write(*****)更改为
item.write(new File(webRootPath+"upload/"+newName+extName));
这样上传文件就保存到webroot下的upload文件夹中了