Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:cn.trymore.core.web.servlet.FileUploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    try {/*from   ww w.  j  ava2  s . c  o m*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(4096);
        diskFileItemFactory.setRepository(new File(this.tempPath));

        String fileIds = "";

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request);
        Iterator<FileItem> itor = fileList.iterator();
        Iterator<FileItem> itor1 = fileList.iterator();
        String file_type = "";
        while (itor1.hasNext()) {
            FileItem item = itor1.next();
            if (item.isFormField() && "file_type".equals(item.getFieldName())) {
                file_type = item.getString();
            }
        }
        FileItem fileItem;
        while (itor.hasNext()) {
            fileItem = itor.next();

            if (fileItem.getContentType() == null) {
                continue;
            }

            // obtains the file path and name
            String filePath = fileItem.getName();

            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            // generates new file name with the current time stamp.
            String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName);
            // ensure the directory existed before creating the file.
            File dir = new File(
                    this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1));
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // stream writes to the destination file
            fileItem.write(new File(this.uploadPath + "/" + newFileName));

            ModelFileAttach fileAttach = null;
            if (request.getParameter("noattach") == null) {
                // storages the file into database.
                fileAttach = new ModelFileAttach();
                fileAttach.setFileName(fileName);
                fileAttach.setFilePath(newFileName);
                fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize()));
                fileAttach.setNote(this.getStrFileSize(fileItem.getSize()));
                fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1));
                fileAttach.setCreatetime(new Date());
                fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL);
                fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat);

                ModelAppUser user = ContextUtil.getCurrentUser();
                if (user != null) {
                    fileAttach.setCreatorId(Long.valueOf(user.getId()));
                    fileAttach.setCreator(user.getFullName());
                } else {
                    fileAttach.setCreator("Unknow");
                }

                this.serviceFileAttach.save(fileAttach);
            }

            //add by Tang ??fileIds?????
            if (fileAttach != null) {
                fileIds = (String) request.getSession().getAttribute("fileIds");
                if (fileIds == null) {
                    fileIds = fileAttach.getId();
                } else {
                    fileIds = fileIds + "," + fileAttach.getId();
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(
                    "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"")
                            + ", \"url\":\"" + newFileName + "\"}}");
        }
        request.getSession().setAttribute("fileIds", fileIds);
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\"");
    }
}

From source file:it.univaq.servlet.Modifica_pub.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {
    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map pubb = new HashMap();
    Map rist = new HashMap();
    Map key = new HashMap();
    Map files = new HashMap();
    Map modifica = new HashMap();

    int id = Integer.parseInt(request.getParameter("id"));

    if (ServletFileUpload.isMultipartContent(request)) {

        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*/*from  w  w w .  j a  v  a2s .co  m*/
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("titolo") || name.equals("autore") || name.equals("descrizione")) {
                    pubb.put(name, value);
                } else if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapubbl")) {
                    rist.put(name, value);
                } else if (name.equals("key1") || name.equals("key2") || name.equals("key3")
                        || name.equals("key4")) {
                    key.put(name, value);
                } else if (name.equals("descrizionemod")) {
                    modifica.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
            }

        }

        pubb.put("idutente", s.getAttribute("userid"));
        modifica.put("userid", s.getAttribute("userid"));
        modifica.put("idpubb", id);

        try {
            //    if(Database.updateRecord("keyword", key, "id="+id)){

            //aggiorno ora la pubblicazione con tutti i dati
            Database.updateRecord("keyword", key, "id=" + id);
            Database.updateRecord("pubblicazione", pubb, "id=" + id);
            Database.updateRecord("ristampa", rist, "idpub=" + id);
            Database.insertRecord("storia", modifica);

            //    //vado alla pagina di corretto inserimento

            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Modifica_pub.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else
        return false;
    return false;
}

From source file:fr.paris.lutece.plugins.directory.business.EntryTypeImg.java

/**
 * {@inheritDoc}//from ww  w  .  j a  v  a  2 s  .  c om
 */
@Override
public void getRecordFieldData(Record record, HttpServletRequest request, boolean bTestDirectoryError,
        boolean bAddNewValue, List<RecordField> listRecordField, Locale locale) throws DirectoryErrorException {
    if (request instanceof MultipartHttpServletRequest) {
        List<FileItem> fileItems = getFileSources(request);

        //if asynchronous file items is empty get the file in the multipart request
        if (CollectionUtils.isEmpty(fileItems)) {
            FileItem fileItem = ((MultipartHttpServletRequest) request)
                    .getFile(PREFIX_ENTRY_ID + this.getIdEntry());

            if (fileItem != null) {
                fileItems = new ArrayList<FileItem>();
                fileItems.add(fileItem);
            }
        }

        if ((fileItems != null) && !fileItems.isEmpty()) {
            // Checks
            if (bTestDirectoryError) {
                this.checkRecordFieldData(fileItems, locale);
            }

            // The index is used to distinguish the thumbnails of one image from another
            int nIndex = 0;

            for (FileItem fileItem : fileItems) {
                String strFilename = (fileItem != null) ? FileUploadService.getFileNameOnly(fileItem)
                        : StringUtils.EMPTY;

                if ((fileItem != null) && (fileItem.get() != null)
                        && (fileItem.getSize() < Integer.MAX_VALUE)) {
                    PhysicalFile physicalFile = new PhysicalFile();
                    physicalFile.setValue(fileItem.get());

                    File file = new File();
                    file.setPhysicalFile(physicalFile);
                    file.setTitle(strFilename);
                    file.setSize((int) fileItem.getSize());
                    file.setMimeType(FileSystemUtil.getMIMEType(strFilename));

                    //Add the image to the record fields list
                    RecordField recordField = new RecordField();
                    recordField.setEntry(this);
                    recordField.setValue(FIELD_IMAGE + DirectoryUtils.CONSTANT_UNDERSCORE + nIndex);
                    recordField.setFile(file);

                    Field fullsizedField = FieldHome.findByValue(this.getIdEntry(), FIELD_IMAGE,
                            PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME));

                    if (fullsizedField != null) {
                        recordField.setField(fullsizedField);
                    }

                    listRecordField.add(recordField);

                    //Create thumbnails records
                    File imageFile = recordField.getFile();
                    Field thumbnailField = FieldHome.findByValue(this.getIdEntry(), FIELD_THUMBNAIL,
                            PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME));

                    if (thumbnailField != null) {
                        byte[] resizedImage = ImageUtil.resizeImage(imageFile.getPhysicalFile().getValue(),
                                String.valueOf(thumbnailField.getWidth()),
                                String.valueOf(thumbnailField.getHeight()), INTEGER_QUALITY_MAXIMUM);

                        RecordField thbnailRecordField = new RecordField();
                        thbnailRecordField.setEntry(this);

                        PhysicalFile thbnailPhysicalFile = new PhysicalFile();
                        thbnailPhysicalFile.setValue(resizedImage);

                        File thbnailFile = new File();
                        thbnailFile.setTitle(imageFile.getTitle());
                        thbnailFile.setExtension(imageFile.getExtension());

                        if ((imageFile.getExtension() != null) && (imageFile.getTitle() != null)) {
                            thbnailFile.setMimeType(FileSystemUtil.getMIMEType(imageFile.getTitle()));
                        }

                        thbnailFile.setPhysicalFile(thbnailPhysicalFile);
                        thbnailFile.setSize(resizedImage.length);

                        thbnailRecordField.setFile(thbnailFile);

                        thbnailRecordField.setRecord(record);
                        thbnailRecordField
                                .setValue(FIELD_THUMBNAIL + DirectoryUtils.CONSTANT_UNDERSCORE + nIndex);
                        thbnailRecordField.setField(thumbnailField);
                        listRecordField.add(thbnailRecordField);
                    }

                    Field bigThumbnailField = FieldHome.findByValue(this.getIdEntry(), FIELD_BIG_THUMBNAIL,
                            PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME));

                    if (bigThumbnailField != null) {
                        byte[] resizedImage = ImageUtil.resizeImage(imageFile.getPhysicalFile().getValue(),
                                String.valueOf(bigThumbnailField.getWidth()),
                                String.valueOf(bigThumbnailField.getHeight()), INTEGER_QUALITY_MAXIMUM);

                        RecordField bigThbnailRecordField = new RecordField();
                        bigThbnailRecordField.setEntry(this);

                        PhysicalFile thbnailPhysicalFile = new PhysicalFile();
                        thbnailPhysicalFile.setValue(resizedImage);

                        File thbnailFile = new File();
                        thbnailFile.setTitle(imageFile.getTitle());
                        thbnailFile.setExtension(imageFile.getExtension());

                        if ((imageFile.getExtension() != null) && (imageFile.getTitle() != null)) {
                            thbnailFile.setMimeType(FileSystemUtil.getMIMEType(imageFile.getTitle()));
                        }

                        thbnailFile.setPhysicalFile(thbnailPhysicalFile);
                        thbnailFile.setSize(resizedImage.length);

                        bigThbnailRecordField.setFile(thbnailFile);

                        bigThbnailRecordField.setRecord(record);
                        bigThbnailRecordField
                                .setValue(FIELD_BIG_THUMBNAIL + DirectoryUtils.CONSTANT_UNDERSCORE + nIndex);
                        bigThbnailRecordField.setField(bigThumbnailField);
                        listRecordField.add(bigThbnailRecordField);
                    }
                }

                nIndex++;
            }
        }

        if (bTestDirectoryError && this.isMandatory() && ((fileItems == null) || fileItems.isEmpty())) {
            RecordField recordField = new RecordField();
            recordField.setEntry(this);
            recordField.setValue(FIELD_IMAGE);
            listRecordField.add(recordField);

            throw new DirectoryErrorException(this.getTitle());
        }
    } else if (bTestDirectoryError) {
        throw new DirectoryErrorException(this.getTitle());
    }
}

From source file:admin.controller.ServletEditPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www  .  jav  a  2 s.c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BRAND_IMAGES_HOME;
        deletePath = AppConstants.BRAND_IMAGES_HOME;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("brandname")) {
                        brandname = fi.getString();
                    }
                    if (fieldName.equals("brandid")) {
                        brandid = fi.getString();
                    }
                    if (fieldName.equals("look")) {
                        lookid = fi.getString();
                    }

                    file_name_to_delete = brand.getFileName(Integer.parseInt(brandid));
                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    //                        int inStr = fileName.indexOf(".");
                    //                        String Str = fileName.substring(0, inStr);
                    //
                    //                        fileName = brandname + "_" + Str + ".jpeg";
                    fileName = brandname + "_" + fileName;
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String file_path = uploadPath + File.separator + fileName;
                    String delete_path = deletePath + File.separator + file_name_to_delete;
                    File deleteFile = new File(delete_path);
                    deleteFile.delete();
                    File storeFile = new File(file_path);
                    fi.write(storeFile);
                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName);
            response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
    } finally {
        out.close();
    }

}

From source file:com.krawler.spring.hrms.common.hrmsExtApplDocsDAOImpl.java

public KwlReturnObject uploadFile(FileItem fi, String userid, HashMap arrparam, String uploadedby)
        throws ServiceException {
    HrmsDocs docObj = new HrmsDocs();
    List ll = new ArrayList();
    int dl = 0;//from ww w  .  ja  v a2s.  c o m
    try {
        String fileName = new String(fi.getName().getBytes(), "UTF8");
        String Ext = "";
        String a = "";

        if (fileName.contains(".")) {
            Ext = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
            a = Ext.toUpperCase();
        }
        if (arrparam.get("IsIE").equals("true")) {
            int cnt = fileName.indexOf("\\");
            while (cnt != -1) {
                fileName = fileName.substring(cnt + 1, fileName.length());
                cnt = fileName.indexOf("\\");
            }
        }
        //            Jobapplicant jobapp = (Jobapplicant) hibernateTemplate.get(Jobapplicant.class, userid);
        //            docObj.setApplicantid(jobapp);
        docObj.setDocname(fileName);
        //            docObj.setDocdesc(docdesc);
        if (StringUtil.isNullOrEmpty((String) arrparam.get("docdesc")) == false) {
            docObj.setDocdesc((String) arrparam.get("docdesc"));
        }
        docObj.setStorename("");
        docObj.setDoctype(a + " " + "File");
        docObj.setUploadedon(new Date());
        docObj.setUploadedby(uploadedby);
        docObj.setStorageindex(1);
        docObj.setDocsize(fi.getSize() + "");
        docObj.setReferenceid(userid);

        hibernateTemplate.save(docObj);

        String fileid = docObj.getDocid();
        if (Ext.length() > 0) {
            fileid = fileid + Ext;
        }
        docObj.setStorename(fileid);

        hibernateTemplate.update(docObj);

        ll.add(docObj);

        //            String temp = "/home/trainee";
        String temp = storageHandlerImplObj.GetDocStorePath();
        uploadFile(fi, temp, fileid);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
}

From source file:ReceiveImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww w .  j av a 2 s . c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println(isMultipart = ServletFileUpload.isMultipartContent(request));

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            System.out.println(fi.isFormField());
            if (fi.isFormField()) {
                System.out.println("Got a form field: " + fi.getFieldName() + " " + fi);
            } else {
                // Get the uploaded file parameters
                //System.out.println(fi.getString("Command"));

                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();

                System.out.println(fieldName);
                System.out.println(fileName);
                String courseHour, course, regNo, date, temp = fileName;
                int j = temp.indexOf("sep");

                courseHour = temp.substring(0, j);
                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                course = temp.substring(0, j);

                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                regNo = temp.substring(0, j);

                date = temp.substring(j + 3);
                date = date.replaceAll("s", "-");

                System.out.println("ualal" + courseHour + course + regNo + date);

                System.out.println(contentType);

                long sizeInBytes = fi.getSize();
                // Write the file

                String uploadFolder = getServletContext().getRealPath("") + "Photo\\" + course + "\\" + regNo
                        + "\\";
                //                    String uploadFolder =  "\\SUST_PHOTO_PRESENT\\Photo\\" + course + "\\" + regNo + "\\";

                uploadFolder = uploadFolder.replace("\\build", "");
                Path path = Paths.get(uploadFolder);
                //if directory exists?
                if (!Files.exists(path)) {
                    try {
                        Files.createDirectories(path);
                    } catch (IOException e) {
                        //fail to create directory
                        e.printStackTrace();
                    }
                }
                //uploadFolder+= "\\"+date+".jpg";   
                System.out.println(fileName);
                System.out.println(uploadFolder);

                //               
                file = new File(uploadFolder + date);

                date = date.replaceAll("-", "/");
                date = date.substring(0, 10);

                String total_url = uploadFolder + date.replaceAll("/", "-") + ".jpg";
                System.out.println(total_url);

                String formattedUrl = total_url.replaceAll("\\\\", "/");

                System.out.println(formattedUrl.substring(38));

                System.out.println("-------------->>>>>>>>" + course + "  " + date + regNo + total_url);

                AddUser.updateUrl(courseHour, course, date, regNo, formattedUrl.substring(38));
                fi.write(file);

                //                    System.out.println("-------------->>>>>>>>" +course+"  "+ date+ regNo+total_url);
                //                   try {
                //            SavePhoto.saveIMG("CSE", "2016", "tada","F:\\1.png");
                //        } catch (IOException ex) {
                //            Logger.getLogger(SavePhoto.class.getName()).log(Level.SEVERE, null, ex);
                //        }
                System.out.println(uploadFolder);
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

/**
 * ???????/*from w w w .ja v  a  2  s . c o  m*/
 * @param klass   ???klass?Class
 * @param filepath   ?
 * @param sizeThreshold   ??
 * @param isFileNameBaseTime   ????
 * @return bean
 */
public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold,
        boolean isFileNameBaseTime) throws Exception {
    FileItemFactory fileItemFactory = null;
    if (sizeThreshold > 0) {
        File repository = new File(filepath);
        fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
    } else {
        fileItemFactory = new DiskFileItemFactory();
    }
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    ServletRequestContext requestContext = new ServletRequestContext(request);
    T bean = null;
    if (klass != null) {
        bean = klass.newInstance();
    }
    // 
    if (ServletFileUpload.isMultipartContent(requestContext)) {
        File parentDir = new File(filepath);

        List<FileItem> fileItemList = upload.parseRequest(requestContext);
        for (int i = 0; i < fileItemList.size(); i++) {
            FileItem item = fileItemList.get(i);
            // ??
            if (item.isFormField()) {
                String paramName = item.getFieldName();
                String paramValue = item.getString("UTF-8");
                log.info("?" + paramName + "=" + paramValue);
                request.setAttribute(paramName, paramValue);
                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);

                        if (field != null) {
                            field.setAccessible(true);
                            Class type = field.getType();
                            if (type == Integer.TYPE) {
                                field.setInt(bean, Integer.valueOf(paramValue));
                            } else if (type == Double.TYPE) {
                                field.setDouble(bean, Double.valueOf(paramValue));
                            } else if (type == Float.TYPE) {
                                field.setFloat(bean, Float.valueOf(paramValue));
                            } else if (type == Boolean.TYPE) {
                                field.setBoolean(bean, Boolean.valueOf(paramValue));
                            } else if (type == Character.TYPE) {
                                field.setChar(bean, paramValue.charAt(0));
                            } else if (type == Long.TYPE) {
                                field.setLong(bean, Long.valueOf(paramValue));
                            } else if (type == Short.TYPE) {
                                field.setShort(bean, Short.valueOf(paramValue));
                            } else {
                                field.set(bean, paramValue);
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?" + paramName);
                    }
                }
            }
            // 
            else {
                // <input type='file' name='xxx'> xxx
                String paramName = item.getFieldName();
                log.info("?" + item.getSize());

                if (sizeThreshold > 0) {
                    if (item.getSize() > sizeThreshold)
                        continue;
                }
                String clientFileName = item.getName();
                int index = -1;
                // ?IE?
                if ((index = clientFileName.lastIndexOf("\\")) != -1) {
                    clientFileName = clientFileName.substring(index + 1);
                }
                if (clientFileName == null || "".equals(clientFileName))
                    continue;

                String filename = null;
                log.info("" + paramName + "\t??" + clientFileName);
                if (isFileNameBaseTime) {
                    filename = buildFileName(clientFileName);
                } else
                    filename = clientFileName;

                request.setAttribute(paramName, filename);

                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);
                        if (field != null) {
                            field.setAccessible(true);
                            field.set(bean, filename);
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?  " + paramName);
                        continue;
                    }
                }

                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                File newfile = new File(parentDir, filename);
                item.write(newfile);
                String serverPath = newfile.getPath();
                log.info("?" + serverPath);
            }
        }
    }
    return bean;
}

From source file:it.infn.ct.molon_portlet.java

/**
 * This method manages the user input fields managing two cases
 * distinguished by the type of the input <form ... statement The use of
 * upload file controls needs the use of "multipart/form-data" while the
 * else condition of the isMultipartContent check manages the standard input
 * case. The multipart content needs a manual processing of all <form items
 * All form' input items are identified by the 'name' input property inside
 * the jsp file//  w  w w .ja v a  2  s.com
 * @param request ActionRequest instance (processAction)
 * @param appInput AppInput instance storing the jobSubmission data
 */

void getInputForm(ActionRequest request, molon_portlet.AppInput appInput) {

    if (PortletFileUpload.isMultipartContent(request)) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            int i = 0;
            int j = 0;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();

                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                switch (molon_portlet.inputControlsIds.valueOf(fieldName)) {

                case jobPID:
                    logstring += LS + "FIELD IS A JOB PID  WITH NAME : '" + item.getString() + "'";
                    appInput.jobPID = item.getString();
                    break;
                case inputURL:
                    logstring += LS + "FIELD IS AN INPUT URL  WITH NAME : '" + item.getString() + "'";
                    appInput.inputURL = item.getString();
                    break;
                case JobIdentifier:
                    logstring += LS + "FIELD IS A JOB IDENTIFIER  WITH NAME : '" + item.getString() + "'";
                    appInput.jobIdentifier = item.getString();
                    break;
                case file_inputFile:
                    if (fileName == "")
                        break;
                    logstring += LS + "FIELD IS A FILE WITH NAME : '" + fileName + "'";
                    appInput.inputFile = appInput.path + "/" + fileName;
                    logstring += LS + "COPYING IT TO PATH : '" + appInput.path + "'";
                    copyFile(item, appInput.inputFile);

                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    } // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        //            appInput.inputFileName = (String) request.getParameter("file_inputFile");
        //            appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");

    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------"
    //                + LS + "inputFileName: '" + appInput.inputFileName + "'"
    //                + LS + "inputFileText: '" + appInput.inputFileText + "'"
            + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS + "jobPID: '" + appInput.jobPID + "'"
            + LS + "inputURL: '" + appInput.inputURL + "'" + LS + "inputFile: '" + appInput.inputFile + "'"
            + LS);

}

From source file:com.jflyfox.modules.filemanager.FileManager.java

public JSONObject add() {
    Iterator<?> it = this.files.iterator();
    if (!it.hasNext()) {
        this.error(lang("INVALID_FILE_UPLOAD"));
        return null;
    }/*from  ww w  .j  a  v a  2 s. c  om*/

    JSONObject fileInfo = null;
    Map<String, String> params = new HashMap<String, String>();
    File tmpFile = null;
    boolean error = false;

    // file field operate
    try {
        FileItem item = null;
        while (it.hasNext()) {
            item = (FileItem) it.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {
                params.put("_fileFieldName", item.getFieldName());
                params.put("_fileName", item.getName());
                params.put(item.getFieldName(), item.getName());

                long maxSize = NumberUtils.parseLong(MAX_SIZE);
                if (getConfig("upload-size") != null) {
                    maxSize = Integer.parseInt(getConfig("upload-size"));
                    if (maxSize != 0 && item.getSize() > (maxSize * 1024 * 1024)) {
                        this.error(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb"));
                        error = true;
                    }
                }

                if (!isImage(item.getName()) && (getConfig("upload-imagesonly") != null
                        && getConfig("upload-imagesonly").equals("true")
                        || this.params.get("type") != null && this.params.get("type").equals("Image"))) {
                    this.error(lang("UPLOAD_IMAGES_ONLY"));
                    error = true;
                }

                if (error) {
                    break;
                }

                tmpFile = new File(
                        this.fileRoot + TMP_PATH + "filemanager_" + System.currentTimeMillis() + ".tmp");
                File filePath = tmpFile.getParentFile();
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                item.write(tmpFile);
            }
        }

    } catch (Exception e) {
        logger.error("INVALID_FILE_UPLOAD", e);
        this.error(lang("INVALID_FILE_UPLOAD"));
    }

    // file rename
    try {
        if (!error && tmpFile != null) {
            String allowed[] = { ".", "-" };

            if ("add".equals(params.get("mode"))) {
                fileInfo = new JSONObject();
                String respPath = "";

                String currentPath = "";
                String fileName = params.get("_fileName");
                String filePath = "";
                try {
                    currentPath = params.get("currentpath");
                    respPath = currentPath;
                    currentPath = new String(currentPath.getBytes("ISO8859-1"), "UTF-8"); // ?
                    currentPath = getFilePath(currentPath);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                filePath = FileManagerUtils.rebulid(this.fileRoot + currentPath);

                LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                strList.put("fileName", fileName);
                fileName = (String) cleanString(strList, allowed).get("fileName");

                if (getConfig("upload-overwrite").equals("false")) {
                    fileName = this.checkFilename(filePath, fileName, 0);
                }

                File saveFile = new File(filePath + fileName);
                tmpFile.renameTo(saveFile);

                fileInfo.put("Path", respPath);
                fileInfo.put("Name", fileName);
                fileInfo.put("Error", "");
                fileInfo.put("Code", 0);
            } else if ("replace".equals(params.get("mode"))) {
                fileInfo = new JSONObject();
                String respPath = "";

                String fileName = "";
                String newFilePath = "";
                String saveFilePath = "";

                try {
                    newFilePath = params.get("newfilepath");
                    newFilePath = new String(newFilePath.getBytes("ISO8859-1"), "UTF-8"); // ?
                    respPath = newFilePath.substring(0, newFilePath.lastIndexOf("/") + 1);
                    fileName = newFilePath.substring(newFilePath.lastIndexOf("/") + 1);
                    newFilePath = getFilePath(newFilePath);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                saveFilePath = FileManagerUtils.rebulid(this.fileRoot + newFilePath);
                File saveFile = new File(saveFilePath);

                LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                strList.put("fileName", fileName);
                fileName = (String) cleanString(strList, allowed).get("fileName");

                if (getConfig("upload-overwrite").equals("false")) {
                    fileName = this.checkFilename(saveFile.getParent(), fileName, 0);
                }

                if (saveFile.exists()) {
                    // before bakup
                    bakupFile(saveFile);
                    // delete src file
                    saveFile.delete();
                }

                tmpFile.renameTo(saveFile);

                fileInfo.put("Path", respPath);
                fileInfo.put("Name", fileName);
                fileInfo.put("Error", "");
                fileInfo.put("Code", 0);
            } else {
                this.error(lang("INVALID_FILE_UPLOAD"));
            }

        }
    } catch (Exception e) {
        logger.error("INVALID_FILE_UPLOAD", e);
        this.error(lang("INVALID_FILE_UPLOAD"));
    }

    // ?
    if (tmpFile.exists()) {
        tmpFile.delete();
    }

    return fileInfo;

}

From source file:it.infn.ct.picalc_portlet.java

/**
 * This method manages the user input fields managing two cases 
 * distinguished by the type of the input <form ... statement
 * The use of upload file controls needs the use of "multipart/form-data"
 * while the else condition of the isMultipartContent check manages the 
 * standard input case. The multipart content needs a manual processing of
 * all <form items/*from  w w  w  .  j  a v  a2  s.  c om*/
 * All form' input items are identified by the 'name' input property
 * inside the jsp file
 * 
 * @param request   ActionRequest instance (processAction)
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void getInputForm(ActionRequest request, AppInput appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                case CpuNumber:
                    appInput.cpuNumber = item.getString();
                    break;
                //case notifyEmail:
                //    appInput.notifyEmail=item.getString();
                //break;
                //case notifyStart:                        
                //    if (item.getString().equalsIgnoreCase("on"))
                //        appInput.notifyStart=true;
                //break;
                //case notifyStop:                        
                //    if (item.getString().equalsIgnoreCase("on"))
                //        appInput.notifyStop=true;
                //break;
                default:
                    // Should not happen unless inputControlsIds enum is not updated
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.cpuNumber = (String) request.getParameter("CpuNumber");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
        //appInput.notifyEmail  = (String)request.getParameter("notifyEmail"  );
        //appInput.notifyStart  =((String)request.getParameter("notifyStart" )).equalsIgnoreCase("on")?true:false;
        //appInput.notifyStop   =((String)request.getParameter("notifyStop"  )).equalsIgnoreCase("on")?true:false;
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "CpuNumber    : '"
            + appInput.cpuNumber + "'" + LS + "JobIdentifier: '" + appInput.jobIdentifier + "'"
            //+LS+"notifyEmail  : '"+appInput.notifyEmail  +"'"
            //+LS+"notifyStart  : '"+appInput.notifyStart  +"'"
            //+LS+"notifyStop   : '"+appInput.notifyStop   +"'"
            + LS);
}