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

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

Introduction

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

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:check_reg_bidder.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {// ww w  .  j av a  2 s .co m

        HttpSession sess = request.getSession(true);
        String f = (String) sess.getAttribute("fn");
        String l = (String) sess.getAttribute("ln");
        String mail = (String) sess.getAttribute("em");
        String un = (String) sess.getAttribute("usr");
        String pwd = (String) sess.getAttribute("pass");
        String add = (String) sess.getAttribute("add");
        String phn = (String) sess.getAttribute("no");
        String cit = (String) sess.getAttribute("city");
        String ut = (String) sess.getAttribute("type");
        String des = (String) sess.getAttribute("des");
        String dept = (String) sess.getAttribute("depa");

        //            out.println(dept);

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=convertToNull", "root", "root");
        Statement st = con.createStatement();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);//retrive req.. data & extract below
        //out.println(isMultipart);
        if (isMultipart) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            String paraname[] = new String[15];
            int i = 0;
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) iterator
                        .next();
                paraname[i] = item.getString();// one by one tag's values to arrat

                //out.println(i+"----"+paraname[i]);
                //out.println("<br>");
                i++;
                if (!item.isFormField())// if type=file
                {
                    String fileName = item.getName();// uploadiing file
                    out.println(fileName);
                    String root = "D:\\rushiraj\\Main Project\\web";//currnet path
                    File path = new File(root + "/cmpfile");// path plus testimage directory
                    if (!path.exists()) {
                        boolean status = path.mkdirs(); //if dir! not exists than createe once
                    }
                    File uploadedFile = new File(path + "/" + fileName); /// upload file/image  at path

                    item.write(uploadedFile);//phiscaly write-
                    String q1 = "insert into company_details (name,pan_no,it_cer,est_date,lic_val,reg_no,address,city,state,class) values('"
                            + paraname[0] + "','" + paraname[1] + "','" + fileName + "','" + paraname[2] + "','"
                            + paraname[3] + "','" + paraname[4] + "','" + paraname[5] + paraname[6]
                            + paraname[7] + "','" + paraname[8] + "','" + paraname[9] + "','" + paraname[10]
                            + "')";
                    String query = "insert into register (first_name,last_name,mail,username,password,phone,address,city,type,designation,department) values('"
                            + f + "','" + l + "','" + mail + "','" + un + "','" + pwd + "','" + phn + "','"
                            + add + "','" + cit + "','" + ut + "','" + des + "','" + dept + "');";
                    out.println(q1);
                    out.println(query);
                    int r = st.executeUpdate(q1);//insert remaing data into table.....
                    int p = st.executeUpdate(query);

                    if (r > 0) {
                        response.sendRedirect("login.jsp");
                    }
                }
            }
        }
    } catch (Exception ex) {
        out.println(ex);
    }

}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/*from   w w  w . j  a v a2  s .c  o  m*/
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:edu.isi.wings.portal.servlets.HandleUpload.java

/**
 * Handle an HTTP POST request from Plupload.
 *//*  w ww.  j  av  a 2s .c  o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Config config = new Config(request);
    if (!config.checkDomain(request, response))
        return;

    Domain dom = config.getDomain();

    String name = null;
    String id = null;
    String storageDir = dom.getDomainDirectory() + "/";
    int chunk = 0;
    int chunks = 0;
    boolean isComponent = false;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                try {
                    InputStream input = item.openStream();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = Streams.asString(input);
                        if ("name".equals(fieldName))
                            name = value.replaceAll("[^\\w\\.\\-_]+", "_");
                        else if ("id".equals(fieldName))
                            id = value;
                        else if ("type".equals(fieldName)) {
                            if ("data".equals(value))
                                storageDir += dom.getDataLibrary().getStorageDirectory();
                            else if ("component".equals(value)) {
                                storageDir += dom.getConcreteComponentLibrary().getStorageDirectory();
                                isComponent = true;
                            } else {
                                storageDir = System.getProperty("java.io.tmpdir");
                            }
                        } else if ("chunk".equals(fieldName))
                            chunk = Integer.parseInt(value);
                        else if ("chunks".equals(fieldName))
                            chunks = Integer.parseInt(value);
                    } else if (name != null) {
                        File storageDirFile = new File(storageDir);
                        if (!storageDirFile.exists())
                            storageDirFile.mkdirs();
                        File uploadFile = new File(storageDirFile.getPath() + "/" + name + ".part");
                        saveUploadFile(input, uploadFile, chunk);
                    }
                } catch (Exception e) {
                    this.printError(out, e.getMessage());
                    e.printStackTrace();
                }
            }
        } catch (FileUploadException e1) {
            this.printError(out, e1.getMessage());
            e1.printStackTrace();
        }
    } else {
        this.printError(out, "Not multipart data");
    }

    if (chunks == 0 || chunk == chunks - 1) {
        // Done upload
        File partUpload = new File(storageDir + File.separator + name + ".part");
        File finalUpload = new File(storageDir + File.separator + name);
        partUpload.renameTo(finalUpload);

        String mime = new Tika().detect(finalUpload);
        if (mime.equals("application/x-sh") || mime.startsWith("text/"))
            FileUtils.writeLines(finalUpload, FileUtils.readLines(finalUpload));

        // Check if this is a zip file and unzip if needed
        String location = finalUpload.getAbsolutePath();
        if (isComponent && mime.equals("application/zip")) {
            String dirname = new URI(id).getFragment();
            location = StorageHandler.unzipFile(finalUpload, dirname, storageDir);
            finalUpload.delete();
        }
        this.printOk(out, location);
    }
}

From source file:com.krawler.spring.crm.emailMarketing.crmEmailMarketingController.java

public ModelAndView saveEmailTemplateFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject result = new JSONObject();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {/*from  w  w w.  j  a  va  2 s  . c o  m*/
        result.put("success", false);
        int file_type = 1;
        String fType = request.getParameter("type");
        if (fType != null && fType.compareTo("img") == 0) {
            file_type = 0;
        }
        String companyid = sessionHandlerImpl.getCompanyid(request);
        String filename = "";
        ServletFileUpload fu = new ServletFileUpload(
                new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, new File("/tmp")));
        if (fu.isMultipartContent(request)) {
            List<FileItem> fileItems = fu.parseRequest(request);
            for (FileItem field : fileItems) {
                if (!field.isFormField()) {
                    String fname = new String(field.getName().getBytes(), "UTF8");
                    String file_id = java.util.UUID.randomUUID().toString();
                    String file_extn = fname.substring(fname.lastIndexOf("."));
                    filename = file_id.concat(file_extn);
                    boolean isUploaded = false;
                    fname = fname.substring(fname.lastIndexOf("\\") + 1);
                    if (field.getSize() != 0) {
                        String basePath = StorageHandler.GetDocStorePath() + companyid + "/" + fType;
                        File destDir = new File(basePath);
                        if (!destDir.exists()) {
                            destDir.mkdirs();
                        }
                        File uploadFile = new File(basePath + "/" + filename);
                        field.write(uploadFile);
                        isUploaded = true;
                        String id = request.getParameter("fileid");
                        if (StringUtil.isNullOrEmpty(id)) {
                            id = file_id;
                        }

                        crmEmailMarketingDAOObj.saveEmailTemplateFile(id, fname, file_extn, new Date(),
                                file_type, sessionHandlerImplObj.getUserid());
                    }
                }
            }
        }
        txnManager.commit(status);
        result.put("success", true);
    } catch (ServiceException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
        try {
            result.put("msg", e.getMessage());
        } catch (Exception je) {
        }
    } catch (UnsupportedEncodingException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
        try {
            result.put("msg", ex.getMessage());
        } catch (Exception je) {
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
        try {
            result.put("msg", e.getMessage());
        } catch (Exception je) {
        }
    }
    return new ModelAndView("jsonView", "model", result.toString());
}

From source file:com.era7.bioinfo.blastxviewer7.server.servlet.UploadBlastAndGetCoverageXMLServlet.java

protected void servletLogic(HttpServletRequest request, HttpServletResponse resp)
        throws javax.servlet.ServletException, java.io.IOException {

    OutputStream out = resp.getOutputStream();

    String temp = request.getParameter(Request.TAG_NAME);

    try {//w ww. j  av a2  s  . c  om

        Request myReq = new Request(temp);

        String method = myReq.getMethod();

        if (method.equals(RequestList.UPLOAD_BLAST_AND_GET_COVERAGE_XML_REQUEST)) {

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (!isMultipart) {
                Response response = new Response();
                response.setError("No file was uploaded");
                out.write(response.toString().getBytes());
            } else {

                System.out.println("all controls passed!!");

                FileItem fileItem = FileUploadUtilities.getFileItem(request);
                InputStream uploadedStream = fileItem.getInputStream();
                BufferedReader inBuff = new BufferedReader(new InputStreamReader(uploadedStream));
                String line = null;
                StringBuilder stBuilder = new StringBuilder();
                while ((line = inBuff.readLine()) != null) {
                    //System.out.println("line = " + line);
                    stBuilder.append(line);
                }

                System.out.println("before blastExporter");

                String resultExport = BlastExporter
                        .exportBlastXMLtoIsotigsCoverage(new BlastOutput(stBuilder.toString()));

                //System.out.println("resultExport = " + resultExport);

                uploadedStream.close();

                System.out.println("after blastexporter");

                String responseSt = "<response status=\"" + Response.SUCCESSFUL_RESPONSE + "\" method=\""
                        + RequestList.UPLOAD_BLAST_AND_GET_COVERAGE_XML_REQUEST + "\" >\n" + resultExport
                        + "\n</response>";

                System.out.println("writing response");

                resp.setContentType("text/html");

                byte[] byteArray = responseSt.getBytes();
                out.write(byteArray);
                resp.setContentLength(byteArray.length);

                System.out.println("doneee!!");

            }

        } else {
            Response response = new Response();
            response.setError("There is no such method");
            out.write(response.toString().getBytes());

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:gov.nih.nci.queue.servlet.FileUploadServlet.java

/**
 * *************************************************
 * URL: /upload doPost(): upload the files and other parameters
 *
 * @param request/*from w  w w.java  2s . c o m*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * **************************************************
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create an object for JSON response.
    ResponseModel rm = new ResponseModel();
    // Set response type to json
    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();

    // Get property values.
    // SOCcer related.
    final Double estimatedThreshhold = Double
            .valueOf(PropertiesUtil.getProperty("gov.nih.nci.soccer.computing.time.threshhold").trim());
    // FileUpload Settings.
    final String repositoryPath = PropertiesUtil.getProperty("gov.nih.nci.queue.repository.dir");
    final String strOutputDir = PropertiesUtil.getProperty("gov.nih.cit.soccer.output.dir").trim();
    final long fileSizeMax = 10000000000L; // 10G
    LOGGER.log(Level.INFO, "repository.dir: {0}, filesize.max: {1}, time.threshhold: {2}",
            new Object[] { repositoryPath, fileSizeMax, estimatedThreshhold });

    // Check that we have a file upload request
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Ensuring that the request is actually a file upload request.
    if (isMultipart) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //upload file dirctory. If it does not exist, create one.
        File f = new File(repositoryPath);
        if (!f.exists()) {
            f.mkdir();
        }
        // Set factory constraints
        // factory.setSizeThreshold(yourMaxMemorySize);
        // Configure a repository
        factory.setRepository(new File(repositoryPath));

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

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

            // Process the uploaded items
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                if (!item.isFormField()) { // Handle file field.
                    String fileName = item.getName();
                    rm.setFileName(fileName);
                    String contentType = item.getContentType();
                    rm.setFileType(contentType);
                    long sizeInBytes = item.getSize();
                    rm.setFileSize(String.valueOf(sizeInBytes));

                    String inputFileId = new UniqueIdUtil(fileName).getInputUniqueID();
                    rm.setInputFileId(inputFileId);
                    String absoluteInputFileName = repositoryPath + File.separator + inputFileId;
                    rm.setRepositoryPath(repositoryPath);

                    // Write file to the destination folder.
                    File inputFile = new File(absoluteInputFileName);
                    item.write(inputFile);

                    // Validation.
                    InputFileValidator validator = new InputFileValidator();
                    List<String> validationErrors = validator.validateFile(inputFile);

                    if (validationErrors == null) { // Pass validation
                        // check estimatedProcessingTime.
                        SoccerServiceHelper soccerHelper = new SoccerServiceHelper(strOutputDir);
                        Double estimatedTime = soccerHelper.getEstimatedTime(absoluteInputFileName);
                        rm.setEstimatedTime(String.valueOf(estimatedTime));
                        if (estimatedTime > estimatedThreshhold) { // STATUS: QUEUE (Ask client for email)
                            // Construct Response String in JSON format.
                            rm.setStatus("queue");
                        } else { // STATUS: PASS (Ask client to confirm calculate)
                            // all good. Process the output and Go to result page directly.
                            rm.setStatus("pass");
                        }
                    } else { // STATUS: FAIL // Did not pass validation.
                        // Construct Response String in JSON format.
                        rm.setStatus("invalid");
                        rm.setDetails(validationErrors);
                    }
                } else {
                    // TODO: Handle Form Fields such as SOC_SYSTEM.
                } // End of isFormField
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "FileUploadException or FileNotFoundException. Error Message: {0}",
                    new Object[] { e.getMessage() });
            rm.setStatus("fail");
            rm.setErrorMessage(
                    "Oops! We met with problems when uploading your file. Error Message: " + e.getMessage());
        }

        // Send the response.
        ObjectMapper jsonMapper = new ObjectMapper();
        LOGGER.log(Level.INFO, "Response: {0}", new Object[] { jsonMapper.writeValueAsString(rm) });
        // Generate metadata file
        new MetadataFileUtil(rm.getInputFileId(), repositoryPath)
                .generateMetadataFile(jsonMapper.writeValueAsString(rm));
        // Responde to the client.
        writer.print(jsonMapper.writeValueAsString(rm));

    } else { // The request is NOT actually a file upload request
        writer.print("You hit the wrong file upload page. The request is NOT actually a file upload request.");
    }
}

From source file:com.manning.cmis.theblend.servlets.AddVersionServlet.java

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

    // check for multipart content
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        // show add version page
        dispatch("addversion.jsp", "Add new version. The Blend.", request, response);
    }/*  w w w.j  av  a  2s.  c o  m*/

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String docId = null;
    boolean major = true;
    ObjectId newId = null;

    // process the request
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(50 * 1024 * 1024);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();

                if (PARAM_DOC_ID.equalsIgnoreCase(name)) {
                    docId = item.getString();
                } else if (PARAM_MAJOR.equalsIgnoreCase(name)) {
                    major = Boolean.parseBoolean(item.getString());
                }
            } else {
                properties.put(PropertyIds.NAME, item.getName());

                uploadedFile = File.createTempFile("blend", "tmp");
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {
        throw new TheBlendException("Upload failed: " + e, e);
    }

    if (uploadedFile == null) {
        throw new TheBlendException("No content!", null);
    }

    try {
        // find the document
        Document doc = CMISHelper.getDocumet(session, docId, CMISHelper.LIGHT_OPERATION_CONTEXT, "document");

        // check out document and get Private Working Copy
        Document pwc = null;
        try {
            // check out
            ObjectId pwcId = doc.checkOut();

            // the PWC must be a document object
            pwc = (Document) session.getObject(pwcId, CMISHelper.LIGHT_OPERATION_CONTEXT);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Checkout failed!", cbe);
        }

        // prepare the content stream
        ContentStream contentStream = null;
        try {
            contentStream = prepareContentStream(session, uploadedFile, doc.getType().getId(), properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // create new version
        try {
            newId = pwc.checkIn(major, properties, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create new version: " + cbe.getMessage(), cbe);
        } finally {
            try {
                contentStream.getStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    } finally {
        // delete temp file
        uploadedFile.delete();
    }

    // show the newly created document
    redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response);
}

From source file:jm.web.Archivo.java

/**
 * Sube un archivo del cliente al servidor Web. Si el archivo ya existe en el
 * servidor Web lo sobrescribe./* w w w. j av a  2 s  .  co m*/
 * @param request. Variable que contiene el request de un formulario.
 * @param tamanioMax. Tamao mximo del archivo en megas.
 * @return Retorna true o false si se subi o no el archivo.
 */
public boolean subir(HttpServletRequest request, double tamanioMax, String[] formato) {
    boolean res = false;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String tipo = item.getContentType();
                    double tamanio = (double) item.getSize() / 1024 / 1024; // para tamao en megas
                    this._archivoNombre = item.getName().replace(" ", "_");
                    this._error = "Se ha excedido el tamao mximo del archivo";
                    if (tamanio <= tamanioMax) {
                        this._error = "El formato del archivo es incorrecto. " + tipo;
                        boolean estaFormato = false;
                        for (int i = 0; i < formato.length; i++) {
                            if (tipo.compareTo(formato[i]) == 0) {
                                estaFormato = true;
                                break;
                            }
                        }
                        if (estaFormato) {
                            this._archivo = new File(this._directorio, this._archivoNombre);
                            item.write(this._archivo);
                            this._error = "";
                            res = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            this._error = e.getMessage();
            e.printStackTrace();
        }
    }
    return res;
}

From source file:com.acciente.commons.htmlform.Parser.java

/**
 * This method parses all the parameters contained in the http servlet request, in particular it parses and
 * merges parameters from the sources listed below. If a parameter is defined in more than on source the higher
 * numbered source below prevails./* ww w. jav a 2  s. c o  m*/
 *
 *    1  - parameters in the URL's query query string (GET params)
 *    2  - parameters submitted using POST including multi-part parameters such as fileuploads
 *
 * @param oRequest a http servlet request object
 * @param iStoreFileOnDiskThresholdInBytes a file size in bytes above which the uploaded file will be stored on disk
 * @param oUploadedFileStorageDir a File object representing a path to which the uploaded files should be saved,
 * if null is specified a temporary directory is created in the java system temp directory path
 *
 * @return a map containing the paramater names and values, the paramter names are keys in the map
 *
 * @throws ParserException thrown if there is an error parsing the parameter data
 * @throws IOException thrown if there is an I/O error
 * @throws FileUploadException thrown if there is an error processing the multi-part data
 */
public static Map parseForm(HttpServletRequest oRequest, int iStoreFileOnDiskThresholdInBytes,
        File oUploadedFileStorageDir) throws ParserException, IOException, FileUploadException {
    Map oGETParams = null;

    // first process the GET parameters (if any)
    if (oRequest.getQueryString() != null) {
        oGETParams = parseGETParams(oRequest);
    }

    Map oPOSTParams = null;

    // next process POST parameters
    if ("post".equals(oRequest.getMethod().toLowerCase())) {
        // check how the POST data has been encoded
        if (ServletFileUpload.isMultipartContent(oRequest)) {
            oPOSTParams = parsePOSTMultiPart(oRequest, iStoreFileOnDiskThresholdInBytes,
                    oUploadedFileStorageDir);
        } else {
            // we have plain text
            oPOSTParams = parsePOSTParams(oRequest);
        }
    }

    Map oMergedParams;

    // merge the GET and POST parameters
    if (oGETParams != null) {
        oMergedParams = oGETParams;

        if (oPOSTParams != null) {
            oMergedParams.putAll(oPOSTParams);
        }
    } else {
        // we know that the oGETParams must be null
        oMergedParams = oPOSTParams;
    }

    return oMergedParams;
}

From source file:it.marcoberri.mbmeteo.action.UploadFile.java

/**
 * Handles the HTTP/*from  www .j ava 2s . c  om*/
 * <code>POST</code> method.
 *
 * @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
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        return;
    }

    // configures some settings
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);

    // constructs the directory path to store upload file
    final String uploadPath = ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.filepath");

    final File uploadDir = new File(uploadPath);

    if (!uploadDir.exists()) {
        FileUtils.forceMkdir(uploadDir);
    }

    try {
        // parses the request's content to extract file data
        final List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            final FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (item.isFormField()) {
                continue;
            }

            final String fileName = new File(item.getName()).getName();
            final String filePath = uploadPath + File.separator + fileName;
            final File storeFile = new File(filePath);
            item.write(storeFile);
        }
        request.setAttribute("message", "Upload has been done successfully!");
    } catch (final Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    final ExecuteImport i = new ExecuteImport();
    Thread t = new Thread(i);
    t.start();

}