Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository.

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

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

/**
 * Handles the HTTP//from  w  w w  .j  ava  2  s . co  m
 * <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();

}

From source file:com.arcadian.loginservlet.CourseContentServlet.java

@Override
public void init() throws ServletException {
    DiskFileItemFactory fileFactory = new DiskFileItemFactory();
    File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
    fileFactory.setRepository(filesDir);
    this.uploader = new ServletFileUpload(fileFactory);
}

From source file:hoot.services.ingest.MultipartSerializer.java

/**
 * Serializes uploaded multipart data into files. It can handle file or folder type.
 * //  w  w  w.  j a  va 2  s .  co m
 * @param jobId = unique id to identify uploaded files group
 * @param inputType = ["FILE" | "DIR"] where DIR type is treated as FGDB
 * @param uploadedFiles = The list of files uploaded
 * @param uploadedFilesPaths = The list of uploaded files paths
 * @param request = The request object that holds post data
 * @throws Exception
 */
public void serializeUpload(final String jobId, String inputType, Map<String, String> uploadedFiles,
        Map<String, String> uploadedFilesPaths, final HttpServletRequest request) throws Exception {
    // Uploaded data container folder path. It is unique to each job
    String repFolderPath = homeFolder + "/upload/" + jobId;
    File dir = new File(repFolderPath);
    FileUtils.forceMkdir(dir);

    if (!ServletFileUpload.isMultipartContent(request)) {
        ResourceErrorHandler.handleError("Content type is not multipart/form-data", Status.BAD_REQUEST, log);
    }
    DiskFileItemFactory fileFactory = new DiskFileItemFactory();
    File filesDir = new File(repFolderPath);
    fileFactory.setRepository(filesDir);
    ServletFileUpload uploader = new ServletFileUpload(fileFactory);

    List<FileItem> fileItemsList = uploader.parseRequest(request);
    Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

    // If user request type is DIR then treat it as FGDB folder
    if (inputType.equalsIgnoreCase("DIR")) {
        _serializeFGDB(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths);

    } else {
        // Can be shapefile or zip file
        _serializeUploadedFiles(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths, repFolderPath);
    }
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @param request/*from  www .  ja  va  2 s.  co  m*/
 * @return Map<String, Object>
 * @throws Exception
 */
public Map<String, Object> parse(HttpServletRequest request) throws Exception {
    String repository = System.getProperty("java.io.tmpdir");
    int maxFileSize = 1024 * 1024 * 1024;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(repository));
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);
    Map<String, Object> map = new HashMap<String, Object>();
    List<?> list = servletFileUpload.parseRequest(request);

    if (list != null && list.size() > 0) {
        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                logger.debug("form field: {}, {}", item.getFieldName(), item.toString());
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
                logger.debug("file field: {}", item.getFieldName());
                map.put(item.getFieldName(), item);
            }
        }
    }
    return map;
}

From source file:ke.co.tawi.babblesms.server.servlet.upload.ContactUpload.java

/**
 *
 * @param config/*from ww w  .j  a v  a 2s. co m*/
 * @throws ServletException
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

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

    File repository = FileUtils.getTempDirectory();
    factory.setRepository(repository);

    uploadUtil = new UploadUtil();

    contactDAO = ContactDAO.getInstance();
    phoneDAO = PhoneDAO.getInstance();
    contactGroupDAO = ContactGroupDAO.getInstance();

    CacheManager mgr = CacheManager.getInstance();
    accountsCache = mgr.getCache(CacheVariables.CACHE_ACCOUNTS_BY_USERNAME);
}

From source file:com.ci6225.marketzone.servlet.seller.AddProductServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)/*from w  ww .j  a v a2 s.  com*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String name = null;
    String description = null;
    String unitPrice = null;
    String quantity = null;
    FileItem imageItem = null;

    // constructs the folder where uploaded file will be stored
    //String uploadFolder = getServletContext().getRealPath("") + "/productImages";
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5000 * 1024);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(5000 * 1024);

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

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("productImage") && !item.getString().equals("")) {
                    imageItem = item;
                }
                System.out.println(item.getFieldName());
            } else {
                System.out.println(item.getFieldName() + " " + item.getString());
                if (item.getFieldName().equals("name")) {
                    name = item.getString();
                } else if (item.getFieldName().equals("description")) {
                    description = item.getString();
                } else if (item.getFieldName().equals("unitPrice")) {
                    unitPrice = item.getString();
                } else if (item.getFieldName().equals("quantity")) {
                    quantity = item.getString();
                }
            }
        }

    } catch (FileUploadException ex) {
        System.out.println(ex);
        ex.printStackTrace();
        response.sendRedirect("./addProduct");
    } catch (Exception ex) {
        System.out.println(ex);
        ex.printStackTrace();
        response.sendRedirect("./addProduct");
    }

    FormValidation validation = new FormValidation();
    List<String> messageList = new ArrayList<String>();
    if (!validation.validateAddProduct(name, description, quantity, unitPrice, imageItem)) {
        messageList.addAll(validation.getErrorMessages());
        request.setAttribute("errorMessage", messageList);
        request.setAttribute("name", name);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("unitPrice", unitPrice);
        RequestDispatcher rd = request.getRequestDispatcher("./addProduct");
        rd.forward(request, response);
    }

    try {
        User user = (User) request.getSession().getAttribute("user");
        productBean.addProduct(name, description, user.getUserId(), Integer.parseInt(quantity),
                Float.parseFloat(unitPrice), imageItem);
        messageList.add("Product Added Successfully.");
        request.setAttribute("successMessage", messageList);
        RequestDispatcher rd = request.getRequestDispatcher("./ViewProductList");
        rd.forward(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        response.sendRedirect("./addProduct");
    }
}

From source file:com.adobe.epubcheck.web.EpubCheckServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    if (!ServletFileUpload.isMultipartContent(req)) {
        out.println("Invalid request type");
        return;//  www  .  j  ava 2s  . co m
    }
    try {
        DiskFileItemFactory itemFac = new DiskFileItemFactory();
        // itemFac.setSizeThreshold(20000000); // bytes
        File repositoryPath = new File("upload");
        repositoryPath.mkdir();
        itemFac.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(itemFac);
        List fileItemList = servletFileUpload.parseRequest(req);
        Iterator list = fileItemList.iterator();
        FileItem book = null;
        while (list.hasNext()) {
            FileItem item = (FileItem) list.next();
            String paramName = item.getFieldName();
            if (paramName.equals("file"))
                book = item;
        }
        if (book == null) {
            out.println("Invalid request: no epub uploaded");
            return;
        }
        File bookFile = File.createTempFile("work", "epub");
        book.write(bookFile);
        EpubCheck epubCheck = new EpubCheck(bookFile, out);
        if (epubCheck.validate())
            out.println("No errors or warnings detected");
        book.delete();
    } catch (Exception e) {
        out.println("Internal Server Error");
        e.printStackTrace(out);
    }
}

From source file:id.go.customs.training.gudang.web.BarangUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Boolean adaFile = ServletFileUpload.isMultipartContent(req);
    if (adaFile) {
        try {/*from  ww w.  j a  va2 s .  com*/
            String lokasiLengkap = req.getServletContext().getRealPath(lokasiPenyimpanan);
            System.out.println("Lokasi hasil upload : " + lokasiLengkap);

            // inisialisasi prosesor upload
            DiskFileItemFactory factory = new DiskFileItemFactory();
            File lokasiSementaraHasilUpload = (File) req.getServletContext()
                    .getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(lokasiSementaraHasilUpload);
            System.out.println("Lokasi upload sementara : " + lokasiSementaraHasilUpload.getAbsolutePath());
            ServletFileUpload prosesorUpload = new ServletFileUpload(factory);

            List<FileItem> hasilUpload = prosesorUpload.parseRequest(req);
            System.out.println("Jumlah file = " + hasilUpload.size());

            for (FileItem fileItem : hasilUpload) {
                System.out.println("----- Informasi File -----");
                System.out.println("Tipe File : " + fileItem.getContentType());
                System.out.println("Nama Field : " + fileItem.getFieldName());
                System.out.println("Nama File : " + fileItem.getName());
                System.out.println("Ukuran File : " + fileItem.getSize());

                String fileTujuan = lokasiLengkap + File.separator + fileItem.getName();
                File tujuan = new File(fileTujuan);
                fileItem.write(tujuan);
                System.out.println("Hasil upload ada di " + fileTujuan);

                HasilImportBarang hasil = BarangImporter.importCsv(tujuan);
                req.setAttribute("hasil", hasil);
            }
        } catch (Exception ex) {
            Logger.getLogger(BarangUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // selesai upload, tampilkan hasil upload
    req.getRequestDispatcher("/WEB-INF/templates/jsp/barang/import.jsp").forward(req, resp);
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files//ww w.j a  v a  2 s.  co m
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

From source file:com.bibisco.filters.FileFilter.java

/**
 * Handling of requests in multipart-encoded format.
 * /*from ww  w .ja  v a  2s.c o m*/
 * <p>Decodes MIME payload and extracts each field and file.
 * 
 * @param pRequest
 * @throws FileUploadException: see Jakarta commons FileUpload library
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void handleIt(ServletRequest pRequest) throws FileUploadException, IOException {
    DiskFileItemFactory lDiskFileItemFactory = new DiskFileItemFactory();
    lDiskFileItemFactory.setSizeThreshold(mIntDiskThreshold);
    lDiskFileItemFactory.setRepository(new File(mStrTmpDir));
    ServletFileUpload lServletFileUpload = new ServletFileUpload(lDiskFileItemFactory);
    lServletFileUpload.setSizeMax(mIntRejectThreshold);

    List<FileItem> lListFileItem = lServletFileUpload.parseRequest((HttpServletRequest) pRequest);
    for (FileItem lFileItem : lListFileItem)
        if (!lFileItem.isFormField()) { // file detected
            mLog.info("elaborating file ", lFileItem.getName());
            processUploadedFile(lFileItem, pRequest);
        } else // regular form field
            processRegularFormField(lFileItem, pRequest);
}