List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:classes.Upload.java
public static String uploadImage(HttpServletRequest request, ServletConfig config, String path) throws FileUploadException, Exception { String url = ""; String imgDir = config.getServletContext().getRealPath(path) + "/"; File dir = new File(imgDir); dir.mkdirs();/* ww w . j ava2 s . c om*/ System.out.println("PasaPorAqui2"); DiskFileItemFactory fabrica = new DiskFileItemFactory(); fabrica.setSizeThreshold(1024); fabrica.setRepository(dir); ServletFileUpload upload = new ServletFileUpload(fabrica); List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { System.out.println("Subiendo"); File archivo = new File(imgDir, item.getName()); item.write(archivo); url = item.getName(); } return url; }
From source file:com.mobiaware.util.UploadHelpers.java
public static File createUploadFile(final HttpServletRequest request) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(THRESHOLD_SIZE); fileItemFactory.setRepository(FileUtils.getTempDirectory()); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); servletFileUpload.setFileSizeMax(MAX_FILE_SIZE); servletFileUpload.setSizeMax(REQUEST_SIZE); File file = null;//from w w w. j ava 2 s .c o m try { FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream fileItem = fileItemIterator.next(); if (fileItem.isFormField()) { // ignore } else { file = File.createTempFile("liim_", null); InputStream is = new BufferedInputStream(fileItem.openStream()); FileUtils.copyInputStreamToFile(is, file); } } } catch (IOException e) { LOG.error(Throwables.getStackTraceAsString(e)); } catch (FileUploadException e) { LOG.error(Throwables.getStackTraceAsString(e)); } return file; }
From source file:com.openmeap.util.ServletUtils.java
/** * @param modelManager/*from www . ja v a2 s.c o m*/ * @param request * @param map * @return * @throws FileUploadException */ static final public Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix, HttpServletRequest request, Map<Object, Object> map) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(fileStoragePrefix)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileUploadSize); List fileItems = upload.parseRequest(request); for (FileItem item : (List<FileItem>) fileItems) { // we'll put this in the parameter map, // assuming the backing that is looking for it // knows what to expect String fieldName = item.getFieldName(); Boolean isFormField = item.isFormField(); Long size = item.getSize(); if (isFormField) { if (size > 0) { map.put(fieldName, new String[] { item.getString() }); } } else if (!isFormField) { map.put(fieldName, item); } } return true; }
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;/*from w w w .j a va2 s. co m*/ 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.fjn.helper.common.io.file.upload.FileUploadHelper.java
/** * ???/*from ww w.j a v a 2 s . co m*/ * @param request * @param encoding encoding ?????character?{@link EncodingUtil} * @return ? * @see {@link #getFormFiledToFileItemMap(HttpServletRequest, String) } * @see {@link ServletFileUpload#parseRequest(HttpServletRequest)} */ public static List<FileItem> getFormFiledItmes(HttpServletRequest request, String encoding) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(defaultSizeThreshold); ServletFileUpload fileUploader = new ServletFileUpload(factory); fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding); List<FileItem> fileItems = null; try { // form? fileItems = fileUploader.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } return fileItems; }
From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java
/** * ???// w w w . j a v a 2 s . c o m * @param request * @param encoding ?????character?{@link EncodingUtil} * @return ? * @see {@link #getFormFiledItmes(HttpServletRequest, String)} * @see {@link ServletFileUpload#parseParameterMap(HttpServletRequest)} */ public static Map<String, List<FileItem>> getFormFiledToFileItemMap(HttpServletRequest request, String encoding) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(defaultSizeThreshold); ServletFileUpload fileUploader = new ServletFileUpload(factory); fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding); Map<String, List<FileItem>> fieldItemMap = null; try { // formfield??FileItem fieldItemMap = fileUploader.parseParameterMap(request); } catch (FileUploadException e) { e.printStackTrace(); } return fieldItemMap; }
From source file:dataMappers.PictureDataMapper.java
public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request) throws FileUploadException, IOException, SQLException { if (!ServletFileUpload.isMultipartContent(request)) { System.out.println("Invalid upload request"); return;// w w w. j av a2 s. co m } // Define limits for disk item DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); // Define limit for servlet upload ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); FileItem itemFile = null; int reportID = 0; // Get list of items in request (parameters, files etc.) List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // Loop items while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { itemFile = item; // If not form field, must be item } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field try { System.out.println(item.getString()); reportID = Integer.parseInt(item.getString()); } catch (NumberFormatException e) { reportID = 0; } } } // This will be null if no fields were declared as image/upload. // Also, reportID must be > 0 if (itemFile != null || reportID == 0) { try { // Create credentials from final vars BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY); // Create client with credentials AmazonS3 s3client = new AmazonS3Client(awsCredentials); // Set region s3client.setRegion(Region.getRegion(Regions.EU_WEST_1)); // Set content length (size) of file ObjectMetadata om = new ObjectMetadata(); om.setContentLength(itemFile.getSize()); // Get extension for file String ext = FilenameUtils.getExtension(itemFile.getName()); // Generate random filename String keyName = UUID.randomUUID().toString() + '.' + ext; // This is the actual upload command s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om)); // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report. PreparedStatement stmt = dbconnector.getCon() .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)"); stmt.setInt(1, reportID); stmt.setString(2, keyName); stmt.executeUpdate(); stmt.close(); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } }
From source file:fr.paris.lutece.util.http.MultipartUtil.java
/** * Convert a HTTP request to a {@link MultipartHttpServletRequest} * @param nSizeThreshold the size threshold * @param nRequestSizeMax the request size max * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise * @param request the HTTP request//w w w . j a v a2s . c om * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content * @throws SizeLimitExceededException exception if the file size is too big * @throws FileUploadException exception if an unknown error has occurred */ public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax, boolean bActivateNormalizeFileName, HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (isMultipart(request)) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(nSizeThreshold); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(nRequestSizeMax); // get encoding to be used String strEncoding = request.getCharacterEncoding(); if (strEncoding == null) { strEncoding = EncodingService.getEncoding(); } Map<String, FileItem> mapFiles = new HashMap<String, FileItem>(); Map<String, String[]> mapParameters = new HashMap<String, String[]>(); List<FileItem> listItems = upload.parseRequest(request); // Process the uploaded items for (FileItem item : listItems) { if (item.isFormField()) { String strValue = StringUtils.EMPTY; try { if (item.getSize() > 0) { strValue = item.getString(strEncoding); } } catch (UnsupportedEncodingException ex) { if (item.getSize() > 0) { // if encoding problem, try with system encoding strValue = item.getString(); } } // check if item of same name already in map String[] curParam = mapParameters.get(item.getFieldName()); if (curParam == null) { // simple form field mapParameters.put(item.getFieldName(), new String[] { strValue }); } else { // array of simple form fields String[] newArray = new String[curParam.length + 1]; System.arraycopy(curParam, 0, newArray, 0, curParam.length); newArray[curParam.length] = strValue; mapParameters.put(item.getFieldName(), newArray); } } else { // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true //all file name will be normalize mapFiles.put(item.getFieldName(), bActivateNormalizeFileName ? new NormalizeFileItem(item) : item); } } return new MultipartHttpServletRequest(request, mapFiles, mapParameters); } return null; }
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 ww w. j a v a 2s . co m*/ } 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.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java
/** * Create an upload handler that will throw an exception if the file is too * large./*from w w w . j a va 2 s. c o m*/ */ private static ServletFileUpload createUploadHandler(HttpServletRequest req, long maxFileSize) { File tempDir = figureTemporaryDirectory(req); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); return upload; }