欢迎来到Java学习网!
设为首页 | 加入收藏
当前位置: 首页 > Java架构 > Servlet >

用到commons-fileupload-1.2.1.jar commons-io-1.4.jar这二个jar包
upload2.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<form action="/upload/UploadServlet" method="post" enctype="multipart/form-data">
username:<input type="text" name="username" /><br/>
password:<input type="password" name="password" /><br/>
file1:<input type="file" name="file1" /><br/>
file2:<input type="file" name="file2" /><br/>
<input type="submit" value="submit" /><br/>
</form>
</body>
</html>

 

UploadServlet.java
package com.test.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = request.getRealPath("/");
factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("gbk");
request.setAttribute(name, value);
} else {
String name = item.getFieldName();
String value = item.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start + 1);
request.setAttribute(name, fileName);
OutputStream os = new FileOutputStream(new File(path, fileName));
InputStream is = item.getInputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.close();
is.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
request.getRequestDispatcher("/upload/result2.jsp").forward(request, response);
}
}

相关教程
推荐内容