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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

@Override
@SuppressWarnings({ "rawtypes" })
protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
        throws ServletException, IOException {

    beforePostStart();/*from   w w  w.  j  ava2  s  . com*/

    final 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(new File("/tmp"));

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
        final List fileItems = upload.parseRequest(req);
        String userHash = null;
        StateToken stateToken = null;
        String typeId = null;
        String fileName = null;
        FileItem file = null;
        for (final Iterator iterator = fileItems.iterator(); iterator.hasNext();) {
            final FileItem item = (FileItem) iterator.next();
            if (item.isFormField()) {
                final String name = item.getFieldName();
                final String value = item.getString();
                LOG.info("name: " + name + " value: " + value);
                if (name.equals(FileConstants.HASH)) {
                    userHash = value;
                }
                if (name.equals(FileConstants.TOKEN)) {
                    stateToken = new StateToken(value);
                }
                if (name.equals(FileConstants.TYPE_ID)) {
                    typeId = value;
                }
            } else {
                fileName = item.getName();
                LOG.info("file: " + fileName + " fieldName: " + item.getFieldName() + " size: " + item.getSize()
                        + " typeId: " + typeId);
                file = item;
            }
        }
        createUploadedFile(userHash, stateToken, fileName, file, typeId);
        onSuccess(response);
    } catch (final FileUploadException e) {
        onFileUploadException(response);
    } catch (final Exception e) {
        onOtherException(response, e);
    }
}

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  w w w  . j  a  v a 2  s .  co  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:com.alibaba.citrus.service.requestcontext.parser.impl.ParameterParserImpl.java

/**
 * ??<a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
 * <code>multipart/form-data</code>HTTP
 * <p>/*from www  .j  ava  2  s.  com*/
 * ?<code>UploadService.automatic</code>???<code>false</code>
 * service?actionservlet
 * </p>
 *
 * @param sizeThreshold  ???0
 * @param sizeMax        HTTP
 * @param repositoryPath ?
 * @throws UploadException ?
 */
public void parseUpload(UploadParameters params) throws UploadException {
    if (uploadProcessed || upload == null) {
        return;
    }

    FileItem[] items = upload.parseRequest(requestContext.getRequest(), params);

    for (FileItem item : items) {
        add(item.getFieldName(), item);
    }

    uploadProcessed = true;

    postProcessParams();
}

From source file:cn.itcast.fredck.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*  w ww . j  a v a 2s .co m*/
 *
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = currentPath + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("Invalid file type: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:it.unisa.tirocinio.servlet.UploadInformationForModuleFilesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww  .  jav  a  2s  .  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, JSONException {

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        out = response.getWriter();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        AdministratorDBOperation getSerialNumberObj = new AdministratorDBOperation();
        ConcreteStaff aAdmin = null;
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String adminSubfolderPath = filePath;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                DateFormat dateFormat = new SimpleDateFormat("yyyy");
                Date date = new Date();
                if (fieldName.equals("modulefile")) {
                    fileToStore = new File(
                            adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Module.pdf");
                } else if (fieldName.equals("registerfile")) {
                    fileToStore = new File(
                            adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Register.pdf");
                }
                fi.write(fileToStore);
                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());
                aAdmin = getSerialNumberObj.getFK_DepartimentbyFK_Account(Integer.parseInt(fi.getString()));
                serialNumber = "" + aAdmin.getFKDepartment();
                adminSubfolderPath += fileSeparator + serialNumber;
                new File(adminSubfolderPath).mkdir();
            }
        }
        message.put("status", 1);
        out.print(message.toString());
    } catch (IOException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:Admin.products.ProductS.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww  w.  j a  v  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        String brand = request.getParameter("sel01n");
        String category_1 = request.getParameter("sel02n");
        String category_2 = request.getParameter("sel03n");
        String category_3 = request.getParameter("sel04n");
        String product_name = request.getParameter("txf01n");
        String description = request.getParameter("txa01n");
        String specifications = request.getParameter("spe00n");

        try {

            String Name = null;
            String Price = null;
            String QTY = null;

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

            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {

                if (fileItem.isFormField()) { //form field

                    //                        fileItem.getFieldName().equals("sel01n")) {
                    Name = fileItem.getString();

                    if (fileItem.getFieldName().equals("spe01n")) {
                        System.out.println("NAME-----:" + Name);
                    } else if (fileItem.getFieldName().equals("spe02n")) {
                        System.out.println("VALUE-----:" + Name);
                    }

                } else {

                    System.out.println("---------------" + fileItem.getName());

                    //                        String n = new File(fileItem.getName()).getName();
                    System.out.println(request.getServletContext().getRealPath("/04_admin/product/img/") + "\\"
                            + System.currentTimeMillis() + ".jpg");
                    fileItem.write(new File(request.getServletContext().getRealPath("/04_admin/product/img/")
                            + "\\" + System.currentTimeMillis() + ".jpg"));
                }
            }

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

From source file:admin.controller.ServletAddLooks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w .  jav  a  2s.  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    super.processRequest(request, response);
    String filePath;
    String fileName, fieldName;
    Looks look;
    RequestDispatcher request_dispatcher;
    String look_name = null;
    Integer organization_id = 0;
    boolean check;
    look = new Looks();
    check = false;

    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        String uploadPath = AppConstants.LOOK_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("/tmp"));

            // 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();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();

                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    try {
                        if (fieldName.equals("lookname")) {
                            look_name = fi.getString();
                        }
                        if (fieldName.equals("organization")) {
                            organization_id = Integer.parseInt(fi.getString());
                        }
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Exception while getting the look_name and organization_id",
                                e);
                    }
                } else {
                    check = look.checkAvailability(look_name, organization_id);

                    if (check == false) {
                        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 = look_name + "_" + Str + ".png";
                        fileName = look_name + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        look.addLooks(look_name, fileName, organization_id);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp?exist=exist");
                    }

                }
            }

        } else {
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while uploading the Looks image", ex);
    }
}

From source file:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java

private Map<String, Object> parseFileItem(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding("UTF-8");
    List<?> items = upload.parseRequest(request);

    Map<String, Object> fields = new HashMap<String, Object>();

    Iterator<?> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            fields.put(item.getFieldName(), item.getString("UTF-8"));
        } else {//from   ww w  . jav a  2 s  .c  om
            fields.put(item.getFieldName(), item);
        }
    }
    return fields;
}

From source file:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java

@SuppressWarnings("unchecked")
@Override/*from w w  w  .ja  v  a  2s  .c om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        ServletRequestContext ctx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(ctx) == false) {
            sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "The servlet can only handle multipart requests." + " This is probably a software bug."));
            return;
        }

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> i = items.iterator();
        HashMap<String, String> params = new HashMap<String, String>();
        HashMap<String, File> files = new HashMap<String, File>();

        while (i.hasNext() == true) {
            FileItem item = i.next();

            if (item.isFormField() == true) {
                String param = item.getFieldName();
                String value = item.getString();
                //                    System.out.println(getClass().getName() + ": param="
                //                            + param + ", value=" + value);
                params.put(param, value);
            } else {
                if (item.getSize() == 0) {
                    continue; // ignore zero-length files
                }

                File tempf = File.createTempFile(request.getRemoteAddr() + "-" + item.getFieldName() + "-", "");
                item.write(tempf);
                files.put(item.getFieldName(), tempf);
                //                    System.out.println("Creating temporary file "
                //                            + tempf.getAbsolutePath());
            }
        }

        // populate, invoke the listener, delete files if needed,
        // send response
        FileUploadAction action = (FileUploadAction) actionClass.newInstance();
        BeanUtils.populate(action, params); // populate the object
        action.setFileList(files);

        FormResponse resp = action.onSubmit(this, request);
        if (resp.isDeleteFiles()) {
            Iterator<Map.Entry<String, File>> j = files.entrySet().iterator();
            while (j.hasNext()) {
                Map.Entry<String, File> entry = j.next();
                File f = entry.getValue();
                f.delete();
            }
        }

        sendResponse(response, resp);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage()));
    }
}

From source file:com.softwarementors.extjs.djn.test.ManualFormUploadSupportTest.java

@DirectFormPostMethod
public Result djnform_test_sendFilesManually(Map<String, String> formParameters,
        Map<String, FileItem> fileFields) {
    assert formParameters != null;
    assert fileFields != null;

    Result r = new Result();
    FileItem file1 = fileFields.get("fileUpload1");
    FileItem file2 = fileFields.get("fileUpload2");
    if (fileFields.size() != 2 || file1 == null || file2 == null) {
        throw new DirectTestFailedException("Unexpected error receiving file fields");
    }/*w  ww  .ja v  a 2 s .c  o m*/

    try {
        r.file1Field = file1.getFieldName();
        r.file1Name = file1.getName();
        if (!r.file1Name.equals("")) {
            r.file1Text = IOUtils.toString(file1.getInputStream());
            file1.getInputStream().close();
        }

        r.file2Field = file2.getFieldName();
        r.file2Name = file2.getName();
        if (!r.file2Name.equals("")) {
            r.file2Text = IOUtils.toString(file2.getInputStream());
            file2.getInputStream().close();
        }
    } catch (IOException e) {
        throw new DirectTestFailedException("Test failed", e);
    }

    return r;
}