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

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

Introduction

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

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static Map<String, Object> parsePostedData(String uploadDirPath, HttpServletRequest httpRequest,
        PrintWriter responseStream) throws Exception {
    File uploadDir = new File(uploadDirPath);
    if (!uploadDir.exists())
        uploadDir.mkdirs();// w w w.j a va2  s. co  m

    Map<String, Object> params = new HashMap<String, Object>();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(httpRequest);
    Iterator<FileItem> fileItemIterator = items.iterator();
    int fileCount = 0;
    while (fileItemIterator.hasNext()) {
        FileItem fileItem = fileItemIterator.next();
        if (fileItem.isFormField()) {
            if (params.get(fileItem.getFieldName()) == null)
                params.put(fileItem.getFieldName(), fileItem.getString());
            List values = (List) params.get(fileItem.getFieldName() + "_List");
            if (values == null) {
                values = new ArrayList();
                params.put(fileItem.getFieldName() + "_List", values);
            }
            values.add(fileItem.getString());
        } else {
            fileCount++;
            String fieldName = fileItem.getFieldName();
            if (fieldName.trim().length() == 0)
                fieldName = "File" + fileCount;
            String fileName = fileItem.getName();
            log.debug("Uploading file number " + fileCount);
            log.debug("FieldName: " + fieldName);
            log.debug("File Name: " + fileName);
            log.debug("ContentType: " + fileItem.getContentType());
            log.debug("Size (Bytes): " + fileItem.getSize());
            if (fileItem.getSize() != 0) {
                try {
                    String tempFileName = "temp" + System.currentTimeMillis() + "-" + fileName;
                    File file = new File(uploadDirPath + "/" + tempFileName);
                    log.debug("FileName: " + file.getAbsolutePath());
                    // write the file
                    fileItem.write(file);
                    if (params.get(fileItem.getFieldName()) == null)
                        params.put(fileItem.getFieldName(), file);
                    else
                        params.put(fileItem.getFieldName() + fileCount, file);
                    List values = (List) params.get(fileItem.getFieldName() + "_List");
                    if (values == null) {
                        values = new ArrayList();
                        params.put(fileItem.getFieldName() + "_List", values);
                    }
                    values.add(file);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warning("Error receiving file:" + e);
                    responseStream.print("error reading (" + fileCount + "): " + fileItem.getName());
                    continue;
                }
            }
        }
    }
    return params;
}

From source file:massbank.FileUpload.java

/**
 * t@CAbv??[h/*ww  w.jav  a2 s. co m*/
 * multipart/form-datat@CAbv??[h
 * s??nullp
 * @return Abv??[ht@C?MAP<t@C, Abv??[h>
 */
@SuppressWarnings("unchecked")
public HashMap<String, Boolean> doUpload() {

    if (fileItemList == null) {
        try {
            fileItemList = (List<FileItem>) parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return null;
        }
    }

    upFileMap = new HashMap<String, Boolean>();
    for (FileItem fItem : fileItemList) {

        // t@CtB?[h??
        if (!fItem.isFormField()) {

            String key = "";
            boolean val = false;

            // t@C?ipX????j
            String filePath = (fItem.getName() != null) ? fItem.getName() : "";

            // t@C?imt@C?j
            String fileName = (new File(filePath)).getName();
            int pos = fileName.lastIndexOf("\\");
            fileName = fileName.substring(pos + 1);
            pos = fileName.lastIndexOf("/");
            fileName = fileName.substring(pos + 1);

            // t@CAbv??[h
            if (!fileName.equals("")) {
                key = fileName;
                File upFile = new File(outPath + "/" + fileName);
                try {
                    fItem.write(upFile);
                    val = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    upFile.delete();
                }
            }
            upFileMap.put(key, val);
        }
    }

    return upFileMap;
}

From source file:com.estampate.corteI.servlet.servlets.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w . j a  v a 2 s  .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, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    HttpSession sesion = request.getSession(true);
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));

                        sesion.setAttribute("sArNombre", String.valueOf(nombre));
                        sesion.setAttribute("sArTipo", String.valueOf(tipo));
                        sesion.setAttribute("sArExtension", String.valueOf(extension));

                        File archivo = new File(dirUploadFiles, "nombreRequest" + extension);
                        item.write(archivo);
                        if (archivo.exists()) {
                            response.sendRedirect("uploadsave.jsp");
                        } else {
                            sesion.setAttribute("sArError", "Ocurrio un error al subir el archiv o");
                            response.sendRedirect("uploaderror.jsp");
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            sesion.setAttribute("sArError", String.valueOf(e.getMessage()));
            response.sendRedirect("uploaderror.jsp");
        } catch (Exception e) {
            sesion.setAttribute("sArError", String.valueOf(e.getMessage()));
            response.sendRedirect("uploaderror.jsp");
        }
    }
    out.close();

}

From source file:com.globalsight.everest.webapp.pagehandler.administration.localepairs.LocalePairImportHandler.java

/**
 * Upload the properties file to FilterConfigurations/import folder
 * /*from  ww  w .j a  v  a2  s. c  om*/
 * @param request
 */
private File uploadFile(HttpServletRequest request) {
    File f = null;
    try {
        String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
                + File.separator + "LocalePairs" + File.separator + "import";
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = tmpDir + File.separator + originalFilePath;
                    f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
        return f;
    } catch (Exception e) {
        logger.error("File upload failed.", e);
        return null;
    }
}

From source file:cpabe.controladores.UploadDecriptacaoServlet.java

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

    List<CaminhoArquivo> lista = new ArrayList<CaminhoArquivo>();
    List<File> lista2 = new ArrayList<File>();

    CaminhoArquivo c = new CaminhoArquivo();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from w  ww. j  a va 2s  . co m

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            c.setNome(nome);
            c.setWay(caminho);

            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            lista2.add(file);
            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
    //lendo a lista dos arquivos adicionados e pegando os caminhos do arquivo e da chave
    c.setWay(lista2.get(0).getAbsolutePath());
    c.setNome(lista2.get(0).getName());
    System.out.println("arquivo=" + lista2.get(0).getAbsolutePath());
    c.setChave(lista2.get(1).getAbsolutePath());
    System.out.println("chave=" + lista2.get(1).getAbsolutePath());

    request.setAttribute("caminho", c);

    request.getRequestDispatcher("/formularios/decriptar/decriptar2.jsp").forward(request, response);

}

From source file:com.stratelia.webactiv.webSites.control.WebSiteSessionController.java

public int addFileIntoWebSite(String webSitePath, FileItem fileItem) throws Exception {
    String fileName = FileUploadUtil.getFileName(fileItem);
    String path = getWebSiteRepositoryPath() + "/" + webSitePath;
    File file = new File(path, fileName);
    fileItem.write(file);
    if (!isInWhiteList(file)) {
        FileUtil.forceDeletion(file);//from www . j a  v  a2s  .com
        return -3;
    }
    return 0;
}

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

/**
 * *************************************************
 * URL: /upload doPost(): upload the files and other parameters
 *
 * @param request/* w w  w. j  av  a  2  s  . co 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.krawler.spring.documents.documentDAOImpl.java

/**
 * @param fi// w  w  w . j a  v a2  s  .co m
 * @param destinationDirectory
 * @param fileName
 * @throws ServiceException
 */
public void uploadFile(FileItem fi, String destinationDirectory, String fileName) throws ServiceException {
    try {
        File destDir = new File(destinationDirectory);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File uploadFile = new File(destinationDirectory + "/" + fileName);
        fi.write(uploadFile);
    } catch (Exception ex) {
        throw ServiceException.FAILURE("documentDAOImpl.uploadFile", ex);
    }

}

From source file:controllers.FrameworkController.java

private void adicionarOuEditarFramework() throws IOException {
    String nome, genero, paginaOficial, id, descricao, caminhoLogo;
    int idLinguagem = -1;
    genero = nome = paginaOficial = descricao = id = caminhoLogo = "";

    File file;//from   ww  w . java  2 s . c om
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = getServletContext();
    String filePath = context.getInitParameter("file-upload");

    String contentType = request.getContentType();

    if ((contentType.contains("multipart/form-data"))) {

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    if (fileName.lastIndexOf("\\") >= 0) {
                        //String name = fileName.substring(fileName.lastIndexOf("\\"), fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    } else {
                        //String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf("."));
                        String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                        file = new File(filePath + name);
                    }
                    caminhoLogo = file.getName();
                    fi.write(file);
                } else {
                    String campo = fi.getFieldName();
                    String valor = fi.getString("UTF-8");

                    switch (campo) {
                    case "nome":
                        nome = valor;
                        break;
                    case "genero":
                        genero = valor;
                        break;
                    case "pagina_oficial":
                        paginaOficial = valor;
                        break;
                    case "descricao":
                        descricao = valor;
                        break;
                    case "linguagem":
                        idLinguagem = Integer.parseInt(valor);
                        break;
                    case "id":
                        id = valor;
                        break;
                    default:
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    boolean atualizando = !id.isEmpty();

    if (atualizando) {
        Framework framework = dao.select(Integer.parseInt(id));

        framework.setDescricao(descricao);
        framework.setGenero(genero);
        framework.setIdLinguagem(idLinguagem);
        framework.setNome(nome);
        framework.setPaginaOficial(paginaOficial);

        if (!caminhoLogo.isEmpty()) {
            File imagemAntiga = new File(filePath + framework.getCaminhoLogo());
            imagemAntiga.delete();

            framework.setCaminhoLogo(caminhoLogo);
        }

        dao.update(framework);

    } else {
        Framework framework = new Framework(nome, descricao, genero, paginaOficial, idLinguagem, caminhoLogo);

        dao.insert(framework);
    }

    response.sendRedirect("frameworks.jsp");
    //response.getWriter().print("<script>window.location.href='frameworks.jsp';</script>");
}

From source file:com.krawler.br.spring.RConverterImpl.java

public Map convertWithFile(HttpServletRequest request, Map reqParams) throws ProcessException {
    HashMap itemMap = new HashMap(), tmpMap = new HashMap();
    try {//from w ww. j a v a 2s  . com
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String key = item.getFieldName();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            if (reqParams.containsKey(key)) {
                if (item.isFormField()) {
                    putItem(tmpMap, key,
                            getValue(item.getString("UTF-8"), mb.getModuleDefinition(o.getType())));
                } else {
                    File destDir = new File(StorageHandler.GetProfileImgStorePath());
                    if (!destDir.exists()) {
                        destDir.mkdirs();
                    }

                    File f = new File(destDir, UUID.randomUUID() + "_" + item.getName());
                    try {
                        item.write(f);
                    } catch (Exception ex) {
                        Logger.getLogger(RConverterImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    putItem(tmpMap, key, f.getAbsolutePath());
                }
            }
        }

        iter = tmpMap.keySet().iterator();

        while (iter.hasNext()) {
            String key = (String) iter.next();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            itemMap.put(key, convertToMultiType((List) tmpMap.get(key), o.getMulti(), o.getType()));
        }

    } catch (FileUploadException ex) {
        throw new ProcessException(ex.getMessage(), ex);
    } catch (UnsupportedEncodingException e) {
        throw new ProcessException(e.getMessage(), e);
    }
    return itemMap;
}