import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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 {
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("hello");
DiskFileItemFactory factory = new DiskFileItemFactory(); //磁盘文件工厂
String path = request.getRealPath("/upload");//上传路径
factory.setRepository(new File(path));
factory.setSizeThreshold(1024*1024);//如果所上传文件大于这个范围则存储在磁盘上,否则放到内存中
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list = null;
try {
list = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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);
try {
item.write(new File(path,fileName));//下面的所有东西用这一句话也可以实现
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// OutputStream os = new FileOutputStream(new File(path,fileName));
// InputStream is = item.getInputStream();
//
// byte[] buffer = new byte[400];
//
// int length = 0;
//
// while((length=is.read(buffer))>0){
//
// os.write(buffer,0,length);
//
// }
//
// os.close();
// is.close();
}
}
request.getRequestDispatcher("/upload/result2.jsp").forward(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}