实现web开发中的文件上传功能,需完成如下二步操作:
FORM元素的enctype属性指定了表单数据向服务器提交时所采用的编码类型,默认的缺省值是“application/x-www-form-
urlencoded”。 然而,在向服务器发送大量的文本、包含非ASCII字符的文本或二进制数据时这种编码方式效率很低。文
件上载时,所使用的编码类型应当是“multipart/form-data”,它既可以发送文本数据,也支持二进制数据上载。Browser
端<form>表单的ENCTYPE属性值为multipart/form-data,它告诉我们传输的数据要用到多媒体传输协议,由于多媒体传
输的都是大量的数据,所以规定上传文件必须是post方法,<input>的type属性必须是file。
上传文件中应当注意的细节:
手工转码,用户名的乱码问题:
paramValue= new String(paramValue.getBytes("iso8859-1"),"utf-8");
利用FileItem类的getString(String encoding)
String getString(String encoding) throws UnsupportedEncodingException
如表示url资源时应该用斜杠 “/”
如表示硬盘路径时用斜杠“\\”
factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));
……
FileItem item;
……
item.delete();
5、 限制文件上传的最大值问题:
调用解析器的:upload.setFileSizeMax(1024*1024); //上传文件不能超过1M。如果超出大小,需要给用户友好提示:
try{
……
}catch (FileUploadBase.FileSizeLimitExceededException e) {
request.setAttribute("message", "上传文件不能超过1M!!");
}
6、 ProgressListener 显示上传进度问题:ProgressListener progressListener = new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("到现在为止, " + pBytesRead + " 字节已上传,总大小为 " + pContentLength);
}
};
upload.setProgressListener(progressListener);<form action="${pageContext.request.contextPath}/servlet/UploadServlet2" enctype="multipart/form-data" method="post">
用户名:<input type="text" name="username" /><br/>
文件1<input type="file" name="file1" /><br/>
文件2<input type="file" name="file2" /><br/>
<input type="submit" value="上传" /><br/>
UploadServlet.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request.setCharacterEncoding("UTF-8");
try {
// 1、建立工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//factory.setRepository(new File("F:\\"));
// 2、得到上传文件解析器
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");//处理上传文件
// 3、设定上传文件尺寸
upload.setFileSizeMax(1024*1024);
// 4、进行解析,得到fileItem对象
List<FileItem> list = upload.parseRequest(request);
// 5、对list进行迭代处理
for (FileItem item : list) {
if (item.isFormField()) {// 表单普通输入项
String paramName = item.getFieldName();
//String paramValue = item.getString();
//paramValue = new String(paramValue.getBytes("ISO8859-1"),"UTF-8");
String paramValue=item.getString("utf-8");
System.out.println("普通输入项" + paramName + "==" + paramValue);
} else {// 上传文件处理
//获取上传文件名
String fileName = item.getName();
// 如果文件xxx中有目录,则去掉目录部分只保留文件名
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
System.out.println("name =" + fileName);
if (!fileName.equals(" ")) {
fileName =refactorFileName(fileName) ;
System.out.println("filename = " + fileName);
InputStream in = item.getInputStream();
File file = new File("F:\\" + fileName);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len - in.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
in.close();
item.delete();
request.setAttribute("message", "文件上传成功");
}
}
}
}catch(FileSizeLimitExceededException e1){
e1.printStackTrace();
request.setAttribute("message", "上传文件尺寸太大!!!");
}catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("message", "文件上传失败!!!");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public String refactorFileName(String fileName){
return UUID.randomUUID().toString() + "_" + fileName;
}
}