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.caltech.ipac.firefly.server.servlets.MultipartDataUtil.java

public static MultiPartData handleRequest(StringKey key, HttpServletRequest req) throws Exception {

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

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

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(req);

    MultiPartData data = new MultiPartData(key);

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

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            data.addParam(name, value);/*w  ww  . j av  a  2  s .  co  m*/
        } else {
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            File uf = new File(ServerContext.getTempWorkDir(), System.currentTimeMillis() + ".upload");
            item.write(uf);
            data.addFile(fieldName, uf, fileName, contentType);
            StringKey fileKey = new StringKey(fileName, System.currentTimeMillis());
            CacheManager.getCache(Cache.TYPE_TEMP_FILE).put(fileKey, uf);
        }
    }
    return data;
}

From source file:Model.Picture.java

private static ArrayList<String> upload_excel(String fileName, FileItem fileItem) throws Exception {
    ArrayList<String> errors = new ArrayList<String>();

    if (Tools.excelExtension(Tools.getExtension(fileName))) {
        new File(Constants.TEMP_DIR).mkdirs();
        File file = new File(Constants.TEMP_DIR + fileName);
        fileItem.write(file);

        errors.addAll(enterUploadedData(fileName));
        file.delete();/*from www.j  a  va  2 s  .co  m*/
    } else
        errors.add(Constants.NOT_EXCEL);

    return errors;
}

From source file:hudson.scm.UserProvidedCredential.java

/**
 * Parses the credential information from a form submission.
 *///  w  ww .  j ava  2  s .com
public static UserProvidedCredential fromForm(StaplerRequest req, MultipartFormDataParser parser)
        throws IOException {
    CrumbIssuer crumbIssuer = Hudson.getInstance().getCrumbIssuer();
    if (crumbIssuer != null && !crumbIssuer.validateCrumb(req, parser))
        throw HttpResponses.error(SC_FORBIDDEN, new IOException("No crumb found"));

    String kind = parser.get("kind");
    int idx = Arrays.asList("", "password", "publickey", "certificate").indexOf(kind);

    String username = parser.get("username" + idx);
    String password = parser.get("password" + idx);

    // SVNKit wants a key in a file
    final File keyFile;
    final FileItem item;
    if (idx <= 1) {
        keyFile = null;
        item = null;
    } else {
        item = parser.getFileItem(kind.equals("publickey") ? "privateKey" : "certificate");
        keyFile = File.createTempFile("hudson", "key");
        if (item != null) {
            try {
                item.write(keyFile);
            } catch (Exception e) {
                throw new IOException2(e);
            }
            if (PuTTYKey.isPuTTYKeyFile(keyFile)) {
                // TODO: we need a passphrase support
                LOGGER.info("Converting " + keyFile + " from PuTTY format to OpenSSH format");
                new PuTTYKey(keyFile, null).toOpenSSH(keyFile);
            }
        }
    }

    return new UserProvidedCredential(username, password, keyFile,
            req.findAncestorObject(AbstractProject.class)) {
        @Override
        public void close() throws IOException {
            if (keyFile != null)
                keyFile.delete();
            if (item != null)
                item.delete();
        }
    };
}

From source file:Model.Picture.java

private static ArrayList<String> upload_picture(String fileName, FileItem fileItem,
        ArrayList<String> pictureNames) throws Exception {
    ArrayList<String> errors = new ArrayList<String>();

    if (Tools.pictureExtension(Tools.getExtension(fileName))) {
        new File(Constants.PICTURE_DIR).mkdirs();
        File file = new File(Constants.PICTURE_DIR + fileName);
        fileItem.write(file);

        pictureNames.add(fileName);// www. ja v  a2 s. co m
    } else
        errors.add(Constants.NOT_PICTURE);

    return errors;
}

From source file:edu.isi.webserver.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request) {
    // Download the file to the upload file folder
    File destinationDir = new File(DESTINATION_DIR_PATH);
    logger.info("File upload destination directory: " + destinationDir.getAbsolutePath());
    if (!destinationDir.isDirectory()) {
        destinationDir.mkdir();/*from  w ww . j ava  2s  .com*/
    }

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

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                System.out.println(item.getFieldName());
                System.out.println(item.getString());
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                System.out.println("File field name: " + item.getFieldName());
                uploadedFile = new File(destinationDir, item.getName());
                item.write(uploadedFile);
                System.out.println("File written to: " + uploadedFile.getAbsolutePath());
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

From source file:edu.isi.karma.util.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request, String destinationDirString) {
    // Download the file to the upload file folder

    File destinationDir = new File(destinationDirString);
    logger.debug("File upload destination directory: " + destinationDir.getAbsolutePath());

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

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;//from   w  ww.j  a  v a  2s.  c  o m
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                uploadedFile = new File(destinationDir, item.getName());
                if (item instanceof DiskFileItem) {
                    DiskFileItem t = (DiskFileItem) item;
                    if (!t.getStoreLocation().renameTo(uploadedFile))
                        item.write(uploadedFile);
                } else
                    item.write(uploadedFile);
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

From source file:com.intbit.FileUploadUtil.java

public static String uploadFile(String uploadPath, HttpServletRequest request)
        throws FileUploadException, Exception {
    logger.info("FileUploadUtil::Entering FileUploadUtil#uploadFile");

    String fileName = null;//  w w  w  . ja v a 2s.  c om
    logger.info("FileUploadUtil::Upload path without filename: " + uploadPath);
    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(AppConstants.TMP_FOLDER));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    // Parse the request to get file items.
    List fileItems = upload.parseRequest(request);

    // Process the uploaded file items
    Iterator i = fileItems.iterator();

    while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();
        if (!(fi.isFormField())) {
            // Get the uploaded file parameters
            fileName = fi.getName();
            if (!"".equals(fileName)) {
                File uploadDir = new File(uploadPath);
                boolean result = false;
                if (!uploadDir.exists()) {
                    result = uploadDir.mkdirs();
                }
                // Write the file
                String filePath = uploadPath + File.separator + fileName;
                logger.info("FileUploadUtil::Upload path with filename" + filePath);
                File storeFile = new File(filePath);
                fi.write(storeFile);
                logger.info("FileUploadUtil::File Uploaded successfully");

            } else {
                throw new IllegalArgumentException("Filename of uploded file cannot be empty");
            }
        }
    }
    return fileName;
}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveFiles(String uploadDir, List<FileItem> list) {

    List filelist = new ArrayList();

    if (list == null) {
        return filelist;
    }/*from   w w  w  .  j  ava  2  s .  c  om*/

    File dir = new File(uploadDir);
    if (!(dir.isDirectory())) {
        dir.mkdirs();
    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        if (!(item.isFormField())) {
            name = item.getName();
            logger.info("saveFiles name=============" + name);

            if (name == null)
                continue;
            if (name.trim().equals("")) {
                continue;
            }

            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }

            File file = null;
            do {
                name = UUID.randomUUID().toString();
                file = new File(uploadPath + name + extName);
            } while (file.exists());

            File saveFile = new File(uploadPath + name + extName);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[(ss.length - 1)]);

            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveLicense(String uploadDir, List<FileItem> list) {

    List<FileInfo> filelist = new ArrayList<FileInfo>();

    if (list == null) {
        return filelist;
    }/*from   ww  w . j a v a2 s.  c  o  m*/

    //?
    //??
    logger.info("saveFiles uploadDir=============" + uploadDir);
    File dir = new File(uploadDir);
    if (!dir.isDirectory()) {
        dir.mkdirs();
    } else {

    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator<FileItem> it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = it.next();
        if (!item.isFormField()) {
            name = item.getName();
            if (name == null || name.trim().equals("")) {
                continue;
            }
            long l = item.getSize();
            logger.info("file size=" + l);
            if (10 * 1024 * 1024 < l) {
                logger.info("File size is greater than 10M!");
                continue;
            }
            name = name.replace("\\", "/");
            if (name.lastIndexOf("/") >= 0) {
                name = name.substring(name.lastIndexOf("/"));
            }
            logger.info("saveFiles name=============" + name);
            File saveFile = new File(uploadPath + name);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[ss.length - 1]);
            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String processFileUpload(HttpServletRequest request, HttpServletResponse response,
        RequestModel req) {//from  ww  w . ja v  a2  s .c  o  m
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads");
    FileOps.createDir(uploadDirName);
    File storageDir = new File(uploadDirName);
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName.length() > 0) {
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    uploadedFile = new File(storageDir, fileName);
                    try {
                        item.write(uploadedFile);
                        uploaded = true;
                    } catch (Exception ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        if (uploaded) {
            return SpServerLogic.getDocUploadResponse(req, uploadedFile);
        } else {
            if (paraMap.containsKey("xmlName")) {
                return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName"));
            }
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}