2010年7月8日 星期四

[Jsp] 檔案上傳(org.apache.commons.fileupload)

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);

List  items = upload.parseRequest(request);
   
   Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
           //一般的request item
            String name = item.getFieldName();
            String value = item.getString();
            out.println(name + "=" + item.getString("UTF-8"));
        } else {
            // 如果是上傳檔案, 就在這接收
            //processUploadedFile(item);
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();
            out.println("fieldName="+fieldName+"");
            out.println("fileName="+fileName+"");
            out.println("contentType="+contentType+"");
            out.println("isInMemory="+isInMemory+"");
            out.println("sizeInBytes="+sizeInBytes+"");
            if (fileName != null && !"".equals(fileName)) {
                fileName= FilenameUtils.getName(fileName);
                out.println("fileName saved="+fileName+"");
                File uploadedFile = new File(saveDirectory, fileName);
                item.write(uploadedFile);
            }
        }
    }           

沒有留言: