以下罗列了简单的三种基于Apache的commons-fileupload上传方式
============================================
所需jar包:
commons-fileupload-1.1.1.jar
commons-io-1.2.jar
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
public class FileUpload extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
private ServletConfig config = null;
private File tempPath = new File("D:\\upload\\temp\\"); // 用于存放临时文件的目录
public void destroy() {
config = null;
super.destroy();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int id = -1;
String uploadPath = config.getInitParameter("uploadPath"); // 用于存放上传文件的目录
res.setContentType("text/html; charset=GB2312");
PrintWriter out = res.getWriter();
System.out.println(req.getContentLength());
System.out.println(req.getContentType());
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(tempPath);
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000);
try {
List fileItems = upload.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator();
// 正则匹配,过滤路径取文件名
String regExp = ".+\\\\(.+)$";
// 过滤掉的文件类型
String[] errorType = { ".exe", ".com", ".cgi", ".jsp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()) {
//getFieldName() ----get form field param
if(item.getFieldName().equals("id")) {
id = Integer.parseInt(item.getString());
}
}
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++) {
if (m.group(1).endsWith(errorType[temp])) {
throw new IOException(name + ": wrong type");
}
}
try {
// 保存上传的文件到指定的目录
// 在下文中上传文件至数据库时,将对这里改写
item.write(new File(uploadPath + id + ".jpg"));
out.print(name + " " + size + "<br>");
} catch (Exception e) {
out.println(e);
}
} else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
out.println(e);
} catch (FileUploadException e) {
out.println(e);
}
}
}
----web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>upload a file to server</description>
<display-name>FileUpload</display-name>
<servlet-name>FileUpload</servlet-name>
<servlet-class>
com.shopping.util.servlet.FileUpload
</servlet-class>
<init-param>
<param-name>uploadPath</param-name>
<param-value>
D:\\share\\JavaProjects\\Shopping\\WebRoot\\images\\product\\
</param-value>
</init-param>
</servlet>
----Web3.0之后基于注解的文件上传
1、Servlet 3.0 对文件上传的支持(源自:http://blog.csdn.net/qq_35928356/article/details/72954893)
Servlet 3.0 改进了部分API,使得Java web 的开发进一步得到简化。
其中两个较大的改进是:
- HttpServletRequest 增加了对文件上传的支持
- ServletContext 允许通过编程的方式动态注册Servlet、Filter
HttpServletRequest 提供了如下两个方法来处理文件上传 :
- Part getPart(String name) : 根据文件上传域name属性来获取上传文件。
- Collection< Part > getParts() :获取所有的文件上传域。
官方文档对这两个方法的说明为:
上面两个方法的返回值都涉及一个API :Part ;每个Part对象对应于一个文件上传域,该对象提供了大量方法来访问上传的文件,如文件类型、大小等。并提供了一个write(String name)将文件写入服务器硬盘。
上传文件表单 :
为了向服务器上传文件,需要在表单里使用 < input type=”file” name=”xxx” …./>文件域,这个文件域会在HTML页面生成一个单行文本框和一个用于“浏览文件”的button。除此之外,表单必须设置enctype属性
enctype属性指定的是表单数据的编码方式,该属性有如下三个值:
- application/x-www-form-urlencoded :这是默认的编码方式,他只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式
- multipart/form-data : 这种方式会以二进制流的方式来处理表单数据,这种编码方式会把 文件域指定文件的内容 (并不是原文件,而是文件内容)也封装到请求参数里
- text/plain : 这种编码方式当表单的action 属性为 mailto:URL 时比较方便,主要用于直接通过表单发送邮件
如果将enctype设置为 application/x-www-form-urlencoded ,或者不设置enctype属性,提交表单时只会发送文件域文本框里的字符串,也就是浏览者所选择文件的绝对路径。这对服务器来说没多大用处,毕竟服务器又无法访问客户机的文件系统。
Servlet实现文件上传代码:
使用Servlet实现文件上传非常简单,不需要commons-fileupload 等工具。注意导入servlet-api.jar
表单示例:
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
Servlet示例:
----Struts2
package com.struts2.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts2.service.PicService;
public class AddPicProAction extends ActionSupport {
private String picName;
private File pic;
private String picFileName;
private String picContentType;
public String getPicName() {
return picName;
}
public void setPicName(String picName) {
this.picName = picName;
}
public File getPic() {
return pic;
}
public void setPic(File pic) {
this.pic = pic;
}
public String getPicFileName() {
return picFileName;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
public String getPicContentType() {
return picContentType;
}
public void setPicContentType(String picContentType) {
this.picContentType = picContentType;
}
public String execute() throws Exception{
//以下是我自己测试路径写的,第一个: 绝对路径,第二个: 项目名/upload,第三个: 通过struts.xml配置文件对当前Action的uploadPath参数赋值(注释掉了),其实和servlet一样的
// String uploadPath =
// ServletActionContext.getServletContext().getRealPath("/upload");
// String uploadPath = ServletActionContext.getServletContext().getContextPath() + "/upload";
// String uploadPath = null;
// ServletActionContext.getRequest().getRealPath(uploadPath);
String uploadPath = "D:\\eclipse-jee-neon-3-win32-x86_64\\workspace\\fileUpload\\WebContent\\upload";
System.out.println(uploadPath);
String newFileName =
UUID.randomUUID().toString() + picFileName.substring(picFileName.lastIndexOf("."));
FileInputStream fis = new FileInputStream(pic);
FileOutputStream fos = new FileOutputStream(uploadPath + "/" + newFileName);
//System.out.println(uploadPath + "/" + newFileName);
byte[] buff = new byte[1024];
int len = 0;
while((len = fis.read(buff)) > 0){
fos.write(buff, 0, len);
}
fis.close();
fos.close();
PicService ps = new PicService();
ps.addPic(picName , newFileName);
return SUCCESS;
}
}
----struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="default" namespace="/" extends="struts-default">
<action name="addPicPro"
class="com.struts2.action.AddPicProAction">
<!-- <param name="uploadPath">D:\\eclipse-jee-neon-3-win32-x86_64\\workspace\\fileUpload\\WebContent\\upload</param>
--> <interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/png</param>
<param name="maximumSize">200000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result type="chain">listPics</result>
<result name="input">/WEB-INF/content/uploadForm.jsp</result>
</action>
<action name="listPics"
class="com.struts2.action.ListPicsAction">
<result>/WEB-INF/content/listPics.jsp</result>
</action>
<action name="*">
<result>/WEB-INF/content/{1}.jsp</result>
</action>
</package>
</struts>