论坛首页 入门技术论坛

临时上传文件的代码

浏览 1267 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-11-01  
周末,没什么事,晒晒一段关于上传文件的代码吧,项目中java实现把excel文件导入服务器端数据库,这样用到了,要把excel文件上传到服务器端,网上有的做法是把文件上传到某路径下,导入后再删除,没必这个必要的,下面代码就可以解决临时上传的功能,有需要的战友可以用一用,如果更好的解决方法,也请多指教啊!
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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 MutiFileTempUpload extends FileUploadBase {
private Map<String, FileItem> files;
    private long filesSize = 0;


    @SuppressWarnings("unchecked")
public Map<String, FileItem> parseRequest(HttpServletRequest request)
            throws UnsupportedEncodingException {

        files = new HashMap<String, FileItem>();

        // Create a factory for disk-based file items

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(sizeThreshold);
       
        if (repository != null)
            factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding(encoding);

        try {
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String value = item.getString(encoding);
                    parameters.put(fieldName, value);
                } else {

                    if (!super.isValidFile(item)) {
                        continue;
                    }
                    if(item.getSize()>0){
                    String fieldName = item.getFieldName();                    
                    files.put(fieldName, item);
                    filesSize += item.getSize();
                    }
                }
            }

        } catch (FileUploadException e) {
            //e.printStackTrace();
        }
        return files;
    }
}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics