Example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.shangde.common.util.FCKConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from  w  w w  .  j  a v  a 2s .  com
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Entering Connector#doPost");

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

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);
        String typePath = null;
        String typeDirPath = null;

        String otherFilePath = this.getServletConfig().getServletContext().getRealPath("/");
        System.out.println("===========" + otherFilePath);

        String fckSavePath = (String) request.getSession().getAttribute("fckSavePath");
        if (fckSavePath != null && !fckSavePath.trim().equals("")) {
            typeDirPath = otherFilePath + "/upload/" + fckSavePath + "/";
        } else {
            typeDirPath = otherFilePath + "/upload/public/";
        }
        //         if("article".equals((request.getSession().getAttribute("fckSavePath")))){//? feceditor.properties
        //            typeDirPath = otherFilePath + "/static/images/";
        //         }else if("exam".equals((request.getSession().getAttribute("exam")))){//? feceditor.properties
        //            typeDirPath = otherFilePath + "/static/images/";
        //         }
        //         else{
        //            typeDirPath = otherFilePath + "/back/upload/fckimage/";
        //         }

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);
        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

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

                // We upload only one file at the same time,
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID() + "." + extension;//

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {//????
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename)) {//????
                        if (fckSavePath != null && !fckSavePath.trim().equals("")) {
                            String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/"
                                    + filename;
                            ur = new UploadResponse(UploadResponse.SC_OK, temp);
                        } else {
                            String temp = "http://import.highso.org.cn/upload/public/" + filename;
                            ur = new UploadResponse(UploadResponse.SC_OK, temp);
                        }

                    } else {//????

                        if (fckSavePath != null && !fckSavePath.trim().equals("")) {
                            String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/"
                                    + filename;
                            ur = new UploadResponse(UploadResponse.SC_RENAMED, temp);
                        } else {
                            String temp = "http://import.highso.org.cn/upload/public/" + filename;
                            ur = new UploadResponse(UploadResponse.SC_RENAMED, temp);
                        }

                    }

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:ch.zhaw.init.walj.projectmanagement.admin.properties.AdminProperties.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart;
    String filePath;/*from www.ja  va  2s .co  m*/
    int maxFileSize = 9000 * 1024;
    int maxMemSize = 4 * 1024;
    File file;

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");

    boolean small = request.getParameter("size").equals("small");

    String message;

    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(this.getServletContext().getRealPath("/") + "img/"));

    // 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<FileItem> fileItems = upload.parseRequest(request);

        // Process the uploaded file items

        for (FileItem fileItem : fileItems) {

            if (!fileItem.isFormField()) {
                // Get the uploaded file parameters
                String contentType = fileItem.getContentType();
                if (contentType.equals("image/png")) {
                    String fileName;
                    if (small) {
                        fileName = "logo_small.png";
                    } else {
                        fileName = "logo.png";
                    }
                    filePath = this.getServletContext().getRealPath("/") + "img/" + fileName;
                    // Write the file
                    file = new File(filePath);
                    fileItem.write(file);
                } else {
                    throw new Exception("type");
                }
            }
        }
        message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                + "<div class=\"callout success\">" + "<h5>Logo uploaded successfully</h5>" + "</div>"
                + "</div>" + "</div>" + "</div>";
        request.setAttribute("msg", message);
    } catch (Exception ex) {

        if (ex.getMessage().equals("type")) {

            message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                    + "<div class=\"callout alert\">" + "<h5>Wrong Type</h5>"
                    + "<p>Please upload a PNG image</p>" + "</div>" + "</div>" + "</div>" + "</div>";
        } else {
            message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                    + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div>" + "</div>"
                    + "</div>" + "</div>";
        }
        request.setAttribute("msg", message);
    }
    doGet(request, response);
}

From source file:com.amalto.core.servlet.UploadFile.java

private void uploadFile(HttpServletRequest req, Writer writer) throws ServletException, IOException {
    // upload file
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new ServletException("Upload File Error: the request is not multipart!"); //$NON-NLS-1$
    }//from w  w w .  j  a v a 2 s.com
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Set upload parameters
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    upload.setFileItemFactory(factory);
    upload.setSizeMax(-1);

    // Parse the request
    List<FileItem> items;
    try {
        items = upload.parseRequest(req);
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    // Process the uploaded items
    if (items != null && items.size() > 0) {
        // Only one file
        Iterator<FileItem> iter = items.iterator();
        FileItem item = iter.next();
        if (LOG.isDebugEnabled()) {
            LOG.debug(item.getFieldName());
        }

        File file = null;
        if (!item.isFormField()) {
            try {
                String filename = item.getName();
                if (req.getParameter(PARAMETER_DEPLOY_JOB) != null) {
                    String contextStr = req.getParameter(PARAMETER_CONTEXT);
                    file = writeJobFile(item, filename, contextStr);
                } else if (filename.endsWith(".bar")) { //$NON-NLS-1$
                    file = writeWorkflowFile(item, filename);
                } else {
                    throw new IllegalArgumentException("Unknown deployment for file '" + filename + "'"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else {
            throw new ServletException("Couldn't process request"); //$NON-NLS-1$);
        }
        String urlRedirect = req.getParameter("urlRedirect"); //$NON-NLS-1$
        if (Boolean.valueOf(urlRedirect)) {
            String redirectUrl = req.getContextPath() + "?mimeFile=" + file.getName(); //$NON-NLS-1$
            writer.write(redirectUrl);
        } else {
            writer.write(file.getAbsolutePath());
        }
    }
    writer.close();
}

From source file:com.runwaysdk.controller.ServletDispatcher.java

/**
 * @param req/*from  ww w  .  j  a va2 s .co  m*/
 * @param annotation
 * @return
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
private Map<String, Parameter> getParameters(HttpServletRequest req, ActionParameters annotation) {
    String mojaxObject = req.getParameter(MOJAX_OBJECT);

    if (mojaxObject != null) {
        try {
            return this.getParameterMap(new MojaxObjectParser(annotation, mojaxObject).getMap());
        } catch (JSONException e) {
            throw new ClientException(e);
        }
    } else {
        if (ServletFileUpload.isMultipartContent(req)) {
            Map<String, Parameter> parameters = new HashMap<String, Parameter>();

            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

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

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

                for (FileItem item : items) {
                    String fieldName = item.getFieldName();

                    if (item.isFormField()) {
                        String fieldValue = item.getString();

                        if (!parameters.containsKey(fieldName)) {
                            parameters.put(fieldName, new BasicParameter());
                        }

                        ((BasicParameter) parameters.get(fieldName)).add(fieldValue);
                    } else if (!item.isFormField() && item.getSize() > 0) {
                        parameters.put(fieldName, new MultipartFileParameter(item));
                    }
                }

                return parameters;
            } catch (FileUploadException e) {
                // Change the exception type
                throw new RuntimeException(e);
            }
        } else {
            return this.getParameterMap(req.getParameterMap());
        }
    }
}

From source file:com.intelligentz.appointmentz.controllers.addSession.java

@SuppressWarnings("Since15")
@Override// w  w w  .j av a2  s.  c o  m
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        String room_id = null;
        String doctor_id = null;
        String start_time = null;
        String date_picked = null;
        ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>();
        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(filePath + "temp"));

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

        // 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
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\"));
                    file = new File(filePath);
                } else {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    file = new File(filePath);
                }
                fi.write(file);
                Files.lines(Paths.get(filePath)).forEach((line) -> {
                    String[] cust = line.split(",");
                    sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim())));
                });
            } else {
                if (fi.getFieldName().equals("room_id"))
                    room_id = fi.getString();
                else if (fi.getFieldName().equals("doctor_id"))
                    doctor_id = fi.getString();
                else if (fi.getFieldName().equals("start_time"))
                    start_time = fi.getString();
                else if (fi.getFieldName().equals("date_picked"))
                    date_picked = fi.getString();
            }
        }

        con = new connectToDB();
        if (con.connect()) {
            Connection connection = con.getConnection();
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = connection.createStatement();
            String SQL, SQL1, SQL2;
            SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)";
            PreparedStatement preparedStmt = connection.prepareStatement(SQL1);
            preparedStmt.setString(1, doctor_id);
            preparedStmt.setString(2, room_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            try {
                java.util.Date d = formatter.parse(date_picked + "-" + start_time);
                Date d_sql = new Date(d.getTime());
                java.util.Date N = new java.util.Date();
                if (N.compareTo(d) > 0) {
                    res.sendRedirect("./error.jsp?error=Invalid Date!");
                }
                //String [] T = start_time.split(":");
                //Time t = Time.valueOf(start_time);
                //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0);

                //java.sql.Time t_sql = new java.sql.Date(d.getTime());
                preparedStmt.setString(4, start_time + ":00");
                preparedStmt.setDate(3, d_sql);
            } catch (ParseException e) {
                displayMessage(res, "Invalid Date!" + e.getLocalizedMessage());
            }

            // execute the preparedstatement
            preparedStmt.execute();

            SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1";
            ResultSet rs = stmt.executeQuery(SQL);

            boolean check = false;
            while (rs.next()) {
                String db_doctor_id = rs.getString("doctor_id");
                String db_date_picked = rs.getString("date");
                String db_start_time = rs.getString("start_time");
                String db_room_id = rs.getString("room_id");

                if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id))
                        && (start_time == null ? db_start_time == null
                                : (start_time + ":00").equals(db_start_time))
                        && (room_id == null ? db_room_id == null : room_id.equals(db_room_id))
                        && (date_picked == null ? db_date_picked == null
                                : date_picked.equals(db_date_picked))) {
                    check = true;
                    //displayMessage(res,"Authentication Success!");
                    SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)";
                    for (SessonCustomer sessonCustomer : sessonCustomers) {
                        preparedStmt = connection.prepareStatement(SQL2);
                        preparedStmt.setString(1, rs.getString("session_id"));
                        preparedStmt.setString(2, sessonCustomer.getMobile());
                        preparedStmt.setInt(3, sessonCustomer.getAppointment_num());
                        preparedStmt.execute();
                    }
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        displayMessage(res, "SQLException");
                    }

                    res.sendRedirect("./home");

                }
            }
            if (!check) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    displayMessage(res, "SQLException");
                }
                displayMessage(res, "SQL query Failed!");
            }
        } else {
            con.showErrormessage(res);
        }

        /*res.setContentType("text/html");//setting the content type
        PrintWriter pw=res.getWriter();//get the stream to write the data
                
        //writing html in the stream
        pw.println("<html><body>");
        pw.println("Welcome to servlet: "+username);
        pw.println("</body></html>");
                
        pw.close();//closing the stream
        */
    } catch (Exception ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex);
        displayMessage(res, "Error!" + ex.getLocalizedMessage());
    }
}

From source file:isl.FIMS.servlet.imports.ImportVocabulary.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("AdminVoc");

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    String file = request.getParameter("file");

    if (ServletFileUpload.isMultipartContent(request)) {
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();//  ww w.  j a v  a2  s  . c  o m
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            ArrayList<String> content = Utils.readFile(storeFile);
            DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser,
                    this.DBpassword);
            Vocabulary voc = new Vocabulary(file, this.lang, vocConf);
            String[] terms = voc.termValues();

            for (int i = 0; i < content.size(); i++) {
                String addTerm = content.get(i);
                if (!Arrays.asList(terms).contains(addTerm)) {
                    voc.addTerm(addTerm);
                }

            }
            Utils.deleteDir(currentDir);
            response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc");
        } catch (Exception ex) {
        }

    }

    xml.append("<FileName>").append(file).append("</FileName>\n");
    xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n");

    xml.append(this.xmlEnd());
    String xsl = conf.IMPORT_Vocabulary;
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:com.hrhih.dispatcher.HrhihJakartaMultiPartRequest.java

private List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir)
        throws FileUploadException {
    DiskFileItemFactory fac = createDiskFileItemFactory(saveDir);
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setProgressListener(new FileUploadListener(servletRequest));// ?
    upload.setSizeMax(maxSize);//from  w  w  w  .jav  a 2 s  . c  o  m
    return upload.parseRequest(createRequestContext(servletRequest));
}

From source file:com.wellmail.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from w w  w  .  j  a v  a  2  s  .c o  m
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

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

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);

                //20k
                else if (uplFile.getSize() > 100 * 1024) {
                    ur = new UploadResponse(204);
                }

                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:dk.clarin.tools.rest.upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    response.setStatus(200);/*  w  w w .j  av  a  2  s  .  co  m*/
    if (!BracMat.loaded()) {
        response.setStatus(500);
        throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason());
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
    *Set the size threshold, above which content will be stored on disk.
    */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    String arg = "(method.POST)"; // bj 20120801 "(action.POST)";

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
        * Parse the request
        */
        @SuppressWarnings("unchecked")
        List<FileItem> items = (List<FileItem>) uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        FileItem theFile = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
            * Handle Form Fields.
            */
            if (item.isFormField()) {
                // We need the job parameter that indirectly tells us what local file name to give to the uploaded file.
                arg = arg + " (\"" + workflow.escape(item.getFieldName()) + "\".\""
                        + workflow.escape(item.getString()) + "\")";
            } else if (item.getName() != "") {
                //Handle Uploaded file.
                if (theFile != null) {
                    response.setStatus(400);
                    /**
                     * getStatusCode$
                     *
                     * Given a HTTP status code and an informatory text, return an HTML-file
                     * with a heading containing the status code and the official short description
                     * of the status code, a paragraph containing the informatory text and a 
                     * paragraph displaying a longer text explaining the code (From wikipedia).
                     * 
                     * This function could just as well have been written in Java.
                     */
                    String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"Too many files uploaded\")");
                    out.println(messagetext);
                    return;
                }
                theFile = item;
            }
        }
        if (theFile != null) {
            /*
            * Write file to the ultimate location.
            */
            /**
             * upload$
             *
             * Make a waiting job non-waiting upon receipt of a result from an 
             * asynchronous tool.
             *
             * Analyze the job parameter. It tells to which job the sent file belongs.
             * The jobs table knows the file name and location for the uploaded file.
             *              (Last field)
             * Input:
             *      List of HTTP request parameters.
             *      One of the parameters must be (job.<jobNr>-<jobID>)
             *
             * Output:
             *      The file name that must be given to the received file when saved in
             *      the staging area.
             *
             * Status codes:
             *      200     ok
             *      400     'job' parameter does not contain hyphen '-' or
             *              'job' parameter missing altogether.
             *      404     Job is not expecting a result (job is not waiting)
             *              Job is unknown
             *      500     Job list could not be read
             *
             * Affected tables:
             *      jobs.table
             */
            String LocalFileName = BracMat.Eval("upload$(" + arg + ")");
            if (LocalFileName == null) {
                response.setStatus(404);
                String messagetext = BracMat
                        .Eval("getStatusCode$(\"404\".\"doPost:" + workflow.escape(LocalFileName) + "\")");
                out.println(messagetext);
            } else if (LocalFileName.startsWith("HTTP-status-code")) {
                /**
                 * parseStatusCode$
                 *
                 * Find the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String statusCode = BracMat
                        .Eval("parseStatusCode$(\"" + workflow.escape(LocalFileName) + "\")");
                response.setStatus(Integer.parseInt(statusCode));
                /**
                 * parsemessage$
                 *
                 * Find the text following the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String messagetext = BracMat.Eval("parsemessage$(\"" + workflow.escape(LocalFileName) + "\")");
                messagetext = BracMat.Eval("getStatusCode$(\"" + workflow.escape(statusCode) + "\".\""
                        + workflow.escape(messagetext) + "\")");
                out.println(messagetext);
            } else {
                File file = new File(destinationDir, LocalFileName);
                try {
                    theFile.write(file);
                } catch (Exception ex) {
                    response.setStatus(500);
                    String messagetext = BracMat
                            .Eval("getStatusCode$(\"500\".\"Tools cannot save uploaded file to "
                                    + workflow.escape(destinationDir + LocalFileName) + "\")");
                    out.println(messagetext);
                    return;
                }
                /**
                 * uploadJobNr$
                 *
                 * Return the string preceding the hyphen in the input.
                 *
                 * Input: <jobNr>-<jobID>
                 */
                String JobNr = BracMat.Eval("uploadJobNr$(" + arg + ")");
                Runnable runnable = new workflow(JobNr, destinationDir);
                Thread thread = new Thread(runnable);
                thread.start();
                response.setStatus(201);
                String messagetext = BracMat.Eval("getStatusCode$(\"201\".\"\")");
                out.println(messagetext);
            }
        } else {
            response.setStatus(400);
            String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"No file uploaded\")");
            out.println(messagetext);
        }
    } catch (FileUploadException ex) {
        response.setStatus(500);
        String messagetext = BracMat.Eval("getStatusCode$(\"500\".\"doPost: FileUploadException "
                + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    } catch (Exception ex) {
        response.setStatus(500);
        String messagetext = BracMat
                .Eval("getStatusCode$(\"500\".\"doPost: Exception " + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    }
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "EenviarMailA.htm", method = RequestMethod.POST)
public String enviarMailA_post(@ModelAttribute("correo") correoNoLeidos c, BindingResult result,
        HttpServletRequest request) {/*from  w ww.ja v  a  2 s.c  om*/
    String mensaje = "";

    try {
        //MultipartFile multipart = c.getArchivo();
        System.out.println("olaEnviarMAILS");
        String ubicacionArchivo = "C:\\DecorakiaReportesIntranet\\archivosMail\\";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

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

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            arc.add(item.getName());
            System.out.println("img" + item.getName());
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:EenviarMail.htm";

}