package view;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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 FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
request.setCharacterEncoding("utf-8");
String filePath=this.getServletContext().getRealPath("/image/product");
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
return;
}
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
//upload.setSizeMax(10*1024*1024);
//factory.setSizeThreshold(256);
//factory.setRepository(new File("D://temp"));
List<FileItem>items=null;
try{
items=upload.parseRequest(request);
}catch(FileUploadException e){
e.printStackTrace();
}
for(FileItem item :items){
if(!item.isFormField()){
String images=new Date().getTime()+".jpg";
HttpSession session = request.getSession();
session.setAttribute("images",images);
File fullFile=new File(item.getName());
File uploadedFile=new File(filePath,images);
try{
item.write(uploadedFile);
}catch(Exception e){
e.printStackTrace();
}
}
}
request.getRequestDispatcher("/admin/shangpinxiangqing.jsp").forward(request, response);
}
}