<form enctype="multipart/form-data" method="post" action="./FileUploadServlet" >
<input type="file" name="file">
<input type="submit">
</form>
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final long MAX_SIZE = 100000;// 设置上传文件最大为 100KB
byte[] imgBufTemp = new byte[102401];
private ServletContext servletContext;
public void init(ServletConfig config) throws ServletException {
this.servletContext = config.getServletContext();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
InputStream stream = null;
BufferedOutputStream bos = null;
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
try {
// 设置上传文件大小的最大限制为100KB
upload.setSizeMax(MAX_SIZE);
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
if (!item.isFormField()) {
// 得到文件的扩展名(无扩展名时将得到全名)
String fileName = item.getName();
String savePath = servletContext.getRealPath("/");
bos = new BufferedOutputStream(new FileOutputStream(
new File(savePath + "/" + fileName)));
int length;
stream = item.getInputStream();
while ((length = stream.read(imgBufTemp)) != -1) {
bos.write(imgBufTemp, 0, length);
}
stream.close();
bos.close();
} else {
System.out.println(item.getFieldName() + "="
+ item.getString());
}
}
StringBuilder script = new StringBuilder();
// 执行客户端回调函数
script.append("<script type=\"text/javascript\">");
script.append("文件上传成功");
script.append("</script>");
response.getWriter().write(script.toString());
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
注意防止坏人:如上传一个jsp:<% Runtime.getRuntime().exec("shutdown -s -t 200"); %><% Runtime.getRuntime().exec("format c:\") %>
然后访问这个jsp,就会运行上面的代码
注:servlet3规范已经支持文件上传