标签:
package cn.itcast.servlet;
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFile extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
//存放文件的真实路径
String path = request.getRealPath("/upload");
factory.setRepository(new File(path));
//文件的大小
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
try{
List<FileItem> list =(List<FileItem>) upload.parseRequest(request);
for(FileItem item : list){
String name = item.getFieldName();
if(item.isFormField()){
String value = item.getString();
System.out.println(name + "=" + value);
request.setAttribute(name, value);
}else{
String value = item.getName();
int start = value.lastIndexOf("\\");
String filename = value.substring(start + 1);
request.setAttribute(name, filename);
item.write(new File(path,filename));
}
}
}catch(Exception e){
e.printStackTrace();
}
request.getRequestDispatcher("uploadResult.jsp").forward(request, response);
}
}
标签:
原文地址:http://www.cnblogs.com/wxm-bk/p/5806613.html