commons_fileupload组件 简单文件上传

1、引入包

     commons-fileupload-1.1.1.jar

     commons-io-1.2.jar

 

2、上传页面

 

   <form action="servlet/FileUploadServlet" method="post" enctype="multipart/form-data" name="form1">
        <input type="file" name="file">
        <input type="submit" name="Submit" value="upload">
   </form>

 

3、 FileUploadServlet.java

 

package com.jsly.drp.basedata.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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 FileUploadServlet extends HttpServlet {

     private File uploadPath = new File("E://"); // 用于存放上传文件的目录
     private File tempPath =new File("E://tmp//"); // 用于存放临时文件的目录
    
     public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
               
         res.setContentType("text/html; charset=GB2312");
         
         DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
         factory.setSizeThreshold(4096);
            // the location for saving data that is larger than getSizeThreshold()
         factory.setRepository(tempPath);
       
         ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum size before a FileUploadException will be thrown
         upload.setSizeMax(1000000 * 20);
       
         try {
            List fileItems = upload.parseRequest(req);//fileItems就是上传文件的集合
            String itemNo = "";
            for(Iterator iter = fileItems.iterator();iter.hasNext();){
                 FileItem item = (FileItem)iter.next();
                 //如果是普通的表单输入域
                 if(item.isFormField()){
                     itemNo = item.getString();
                 }
                
                 //如果不是普通的表单输入域,也就是文件域
                 if (!item.isFormField()) {
                     String fileName = item.getName();
                     long size = item.getSize();
                     if((fileName==null||fileName.equals("")) && size==0){
                         continue;
                     }
                     //截取字符串,如D:/addnetFile/a.txt
                     fileName = fileName.substring(fileName.lastIndexOf("//") + 1, fileName.length());
                     item.write(new File(uploadPath, fileName));
                     itemManager.uploadItemImage(itemNo, fileName);
                 }  
            }
          }catch (Exception e) {
            e.printStackTrace();
          }
     }
     
}

 

注:

commons_fileupload组件 简单文件上传_第1张图片

你可能感兴趣的:(exception,String,upload,File,iterator,input)