jsp/servlet文件上传整理
一、采用的架包
commons-fileupload-1.2.1.jar、commons-io-1.4.jar
二、jsp页面如下
file_upload.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>文件上传演示例子</title>
</head>
<body>
<h3>文件上传</h3>
<hr />
<form action="fileUpload" method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>
</td>
<td>
<input type="file" name="file" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="文件上传" />
</td>
</tr>
</table>
</form>
</body>
</html>
三、servlet代码
FileUploadServlet.java
package com.util;
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
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;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// 采用apache工具包进行文件上传操作
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fileitems = upload.parseRequest(request);
for (FileItem item : fileitems) {
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
// 转换下字符集编码
value = new String(value.getBytes("iso-8859-1"), "utf-8");
System.out.println(name + "=" + value);
} else {
String filename = item.getName();
//System.out.println(filename);
ServletContext context = getServletContext();
// 上传的文件存放路径为...\\WebRoot\\upload\\filename
String dir = context.getRealPath("upload");
File file = new File(dir, filename);
file.createNewFile();
// 获得流,读取数据写入文件
InputStream in = item.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
int len;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0)
fos.write(buffer, 0, len);
// 关闭资源文件操作
fos.close();
in.close();
// 删除临时文件
item.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、web.xml配置如下
<servlet>
<servlet-name>fileUpload</servlet-name>
<servlet-class>com.shopping.util.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUpload</servlet-name>
<url-pattern>/fileUpload</url-pattern>
</servlet-mapping>