多文件上传后台代码的实现:
- /**
- * 文件上传实例
- * @author samLee
- *
- */
- public class UploadPhotoServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public UploadPhotoServlet() {
- super();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doPost(request, response);
- }
- @SuppressWarnings("unchecked")
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //文件存放的目录
- File tempDirPath =new File(request.getSession().getServletContext().getRealPath("/")+"\\upload\\");
- if(!tempDirPath.exists()){
- tempDirPath.mkdirs();
- }
- //创建磁盘文件工厂
- DiskFileItemFactory fac = new DiskFileItemFactory();
- //创建servlet文件上传组件
- ServletFileUpload upload = new ServletFileUpload(fac);
- //文件列表
- List fileList = null;
- //解析request从而得到前台传过来的文件
- try {
- fileList = upload.parseRequest(request);
- } catch (FileUploadException ex) {
- ex.printStackTrace();
- return;
- }
- //保存后的文件名
- String imageName = null;
- //便利从前台得到的文件列表
- Iterator<FileItem> it = fileList.iterator();
- while(it.hasNext()){
- FileItem item = it.next();
- //如果不是普通表单域,当做文件域来处理
- if(!item.isFormField()){
- imageName = new Date().getTime()+Math.random()*10000+item.getName();
- BufferedInputStream in = new BufferedInputStream(item.getInputStream());
- BufferedOutputStream out = new BufferedOutputStream(
- new FileOutputStream(new File(tempDirPath+"\\"+imageName)));
- Streams.copy(in, out, true);
- }
- }
- //
- PrintWriter out = null;
- try {
- out = encodehead(request, response);
- } catch (IOException e) {
- e.printStackTrace();
- }
- //这个地方不能少,否则前台得不到上传的结果
- out.write("1");
- out.close();
- }
- /**
- * Ajax辅助方法 获取 PrintWriter
- * @return
- * @throws IOException
- * @throws IOException
- * request.setCharacterEncoding("utf-8");
- response.setContentType("text/html; charset=utf-8");
- */
- private PrintWriter encodehead(HttpServletRequest request,HttpServletResponse response) throws IOException{
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html; charset=utf-8");
- return response.getWriter();
- }
- }