Java Code Examples for org.apache.commons.fileupload.disk.DiskFileItemFactory

The following are top voted examples for showing how to use org.apache.commons.fileupload.disk.DiskFileItemFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: iBase4J-Common   File: UploadUtil.java   Source Code and License 8 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
 
Example 2
Project: JAVA-   File: UploadUtil.java   Source Code and License 8 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 3
Project: automat   File: UploadUtil.java   Source Code and License 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 4
Project: mumu   File: UploadUtil.java   Source Code and License 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 5
Project: iBase4J   File: UploadUtil.java   Source Code and License 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
    if (!saveDir.isDirectory()) {
        saveDir.mkdir();
    }
    List<?> fileItems = null;
    RequestContext requestContext = new ServletRequestContext(request);
    if (FileUpload.isMultipartContent(requestContext)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(saveDir);
        factory.setSizeThreshold(fileSizeThreshold);
        ServletFileUpload upload = new ServletFileUpload(factory);
        fileItems = upload.parseRequest(request);
    }
    return fileItems;
}
 
Example 6
Project: mumu-core   File: UploadUtil.java   Source Code and License 7 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 7
Project: osframe   File: UploadUtil.java   Source Code and License 7 votes vote down vote up
/** 获取所有文本域 */
public static List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 8
Project: struts2   File: JakartaMultiPartRequest.java   Source Code and License 7 votes vote down vote up
protected DiskFileItemFactory createDiskFileItemFactory(String saveDir) {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }
    return fac;
}
 
Example 9
Project: jeecms6   File: SnapScreenServlet.java   Source Code and License 7 votes vote down vote up
private InputStream getInputStreamFromRequest(HttpServletRequest request) {
	InputStream inputStream=null;
	DiskFileItemFactory dff = new DiskFileItemFactory();
	try {
		ServletFileUpload sfu = new ServletFileUpload(dff);
		FileItemIterator fii = sfu.getItemIterator(request);
		while (fii.hasNext()) {
			FileItemStream item = fii.next();
			// 普通参数存储
			if (!item.isFormField()) {
				// 只保留一个
				if (inputStream == null) {
					inputStream = item.openStream();
					return inputStream;
				}
			} 
		}
	} catch (Exception e) {
	}
	return inputStream;
}
 
Example 10
Project: xslweb   File: RequestSerializer.java   Source Code and License 7 votes vote down vote up
private List<FileItem> getMultipartContentItems() throws IOException, FileUploadException {
  List<FileItem> items = null;
  boolean isMultipart = ServletFileUpload.isMultipartContent(req);    
  if (isMultipart) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    reposDir = new File(FileUtils.getTempDirectory(), File.separatorChar + UUID.randomUUID().toString());
    if (!reposDir.mkdirs()) {
      throw new XSLWebException(String.format("Could not create DiskFileItemFactory repository directory (%s)", reposDir.getAbsolutePath()));
    }
    factory.setRepository(reposDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1024 * 1024 * webApp.getMaxUploadSize());
    items = upload.parseRequest(req);      
  }
  return items;
}
 
Example 11
Project: jawn   File: JawnServletContext.java   Source Code and License 7 votes vote down vote up
/**
 * Gets the FileItemIterator of the input.
 * 
 * Can be used to process uploads in a streaming fashion. Check out:
 * http://commons.apache.org/fileupload/streaming.html
 * 
 * @return the FileItemIterator of the request or null if there was an
 *         error.
 */
public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize());
    factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir());
    //README the file for tmpdir *MIGHT* need to go into Properties
    
    ServletFileUpload upload = new ServletFileUpload(factory);
    
    if(encoding != null)
        upload.setHeaderEncoding(encoding);
    upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE));
    
    try {
        List<FormItem> items = upload.parseRequest(request)
                .stream()
                .map(item -> new ApacheFileItemFormItem(item))
                .collect(Collectors.toList());
        return Optional.of(items);
    } catch (FileUploadException e) {
        //"Error while trying to process mulitpart file upload"
        //README: perhaps some logging
    }
    return Optional.empty();
}
 
Example 12
Project: OLE-INST   File: DocumentResources.java   Source Code and License 7 votes vote down vote up
private ArrayList<File> extractBagFilesFromRequest(@Context HttpServletRequest req,
                                                   @Context HttpServletResponse res) throws Exception {
    File targetDir = null;
    try {
        File file = null;
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
        Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
        while (items.hasNext()) {
            FileItem item = (FileItem) items.next();
            LOG.info("item Name = " + item.getName() + " ; content type = " + item.getContentType());
            file = new File(FileUtils.getTempDirectory(), item.getName());
            item.write(file);
        }
        targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null);
        LOG.info("extractedBagFileLocation " + targetDir);
    } catch (IOException e) {
        LOG.error("IOException", e);
        sendResponseBag(res, e.getMessage(), "failure");
    } catch (FormatHelper.UnknownFormatException unknownFormatException) {
        LOG.error("unknownFormatException", unknownFormatException);
        sendResponseBag(res, unknownFormatException.getMessage(), "failure");
    }
    return compressUtils.getAllFilesList(targetDir);
}
 
Example 13
Project: odo   File: HttpUtilities.java   Source Code and License 7 votes vote down vote up
/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
 * as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
 * multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart
 * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 */
@SuppressWarnings("unchecked")
public static void handleMultipartPost(
    EntityEnclosingMethod postMethodProxyRequest,
    HttpServletRequest httpServletRequest,
    DiskFileItemFactory diskFileItemFactory)
    throws ServletException {
    // TODO: this function doesn't set any history data
    try {
        // just pass back the binary data
        InputStreamRequestEntity ire = new InputStreamRequestEntity(httpServletRequest.getInputStream());
        postMethodProxyRequest.setRequestEntity(ire);
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, httpServletRequest.getHeader(STRING_CONTENT_TYPE_HEADER_NAME));
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
Example 14
Project: drinkwater-java   File: FileUploadProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ExchangeFileUpload upload = new ExchangeFileUpload(factory);

    java.util.List<FileItem> items = upload.parseExchange(exchange);

    if(items.size() >= 1){
        exchange.getIn().setBody(items.get(0).getInputStream());

        for (int i = 1; i < items.size(); i++) {
            exchange.setProperty(items.get(i).getName(), items.get(i).getInputStream());
        }
    }
}
 
Example 15
Project: urule   File: FrameServletHandler.java   Source Code and License 6 votes vote down vote up
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	boolean overwriteProject=true;
	List<FileItem> items = upload.parseRequest(req);
	if(items.size()==0){
		throw new ServletException("Upload file is invalid.");
	}
	for(FileItem item:items){
		String name=item.getFieldName();
		if(name.equals("overwriteProject")){
			String overwriteProjectStr=new String(item.get());
			overwriteProject=Boolean.valueOf(overwriteProjectStr);
		}else if(name.equals("file")){
			inputStream=item.getInputStream();
		}
	}
	repositoryService.importXml(inputStream,overwriteProject);
	IOUtils.closeQuietly(inputStream);
	resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
 
Example 16
Project: urule   File: PackageServletHandler.java   Source Code and License 6 votes vote down vote up
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory=new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	List<FileItem> items = upload.parseRequest(req);
	Iterator<FileItem> itr = items.iterator();
	List<Map<String,Object>> mapData=null;
	while (itr.hasNext()) {
		FileItem item = (FileItem) itr.next();
		String name=item.getFieldName();
		if(!name.equals("file")){
			continue;
		}
		InputStream stream=item.getInputStream();
		mapData=parseExcel(stream);
		httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
		stream.close();
		break;
	}
	httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
	writeObjectToJson(resp, mapData);
}
 
Example 17
Project: convertigo-engine   File: UploadService.java   Source Code and License 6 votes vote down vote up
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
	// Check that we have a file upload request
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);

	if (!isMultipart)
		throw new IllegalArgumentException("Not multipart content!");

	FileItemFactory factory = new DiskFileItemFactory();

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

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

	// Process the uploaded items
	handleFormFields(request);
	for (FileItem item : items) {
		doUpload(request, document, item);
	}
}
 
Example 18
Project: oryx2   File: AbstractOryxResource.java   Source Code and License 6 votes vote down vote up
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException {
  if (sharedFileItemFactory.get() == null) {
    // Not a big deal if two threads actually set this up
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(
        1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir"));
    fileItemFactory.setFileCleaningTracker(
        FileCleanerCleanup.getFileCleaningTracker(servletContext));
    sharedFileItemFactory.compareAndSet(null, fileItemFactory);
  }

  try {
    return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request)
        .stream().map(FileItemPart::new).collect(Collectors.toList());
  } catch (FileUploadException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example 19
Project: drinkwater-java   File: FileUploadProcessor.java   Source Code and License 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ExchangeFileUpload upload = new ExchangeFileUpload(factory);

    java.util.List<FileItem> items = upload.parseExchange(exchange);

    if(items.size() >= 1){
        exchange.getIn().setBody(items.get(0).getInputStream());

        for (int i = 1; i < items.size(); i++) {
            exchange.setProperty(items.get(i).getName(), items.get(i).getInputStream());
        }
    }
}
 
Example 20
Project: carbon   File: MultipartFormKeyValueRequestMapper.java   Source Code and License 6 votes vote down vote up
public Map<String, Object> map(HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setSizeMax(20 * 1024);
    upload.setFileSizeMax(10 * 1024);

    List<FileItem> items;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new RequestMappingException("", e);
    }

    return items.stream().map(item -> {
        String key = item.getFieldName();
        if (item.isFormField()) {
            String value = item.getString();
            return new SimpleKeyValue<String, Object>(key, value);
        } else {
            return new SimpleKeyValue<String, Object>(key, item);
        }
    }).collect(Collectors.toMap(
            SimpleKeyValue::getKey,
            SimpleKeyValue::getValue
    ));
}
 
Example 21
Project: openbravo-brazil   File: VariablesBase.java   Source Code and License 6 votes vote down vote up
/**
 * Basic constructor that takes the request object and saves it to be used by the subsequent
 * methods
 * 
 * @param request
 *          HttpServletRequest object originating from the user request.
 */
@SuppressWarnings("unchecked")
public VariablesBase(HttpServletRequest request) {
  if (request == null) {
    // logging exception to obtain stack trace to pinpoint the cause
    log4j.warn("Creating a VariablesBase with a null request", new Exception());
    this.session = new HttpSessionWrapper();
    this.isMultipart = false;
  } else {
    this.session = request.getSession(true);
    this.httpRequest = request;
    this.isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
    if (isMultipart) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // factory.setSizeThreshold(yourMaxMemorySize);
      // factory.setRepositoryPath(yourTempDirectory);
      ServletFileUpload upload = new ServletFileUpload(factory);
      // upload.setSizeMax(yourMaxRequestSize);
      try {
        items = upload.parseRequest(request);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
}
 
Example 22
Project: communote-server   File: AttachmentResourceHandler.java   Source Code and License 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AttachmentIsEmptyException
 *             Thrown, when the attachment is of zero size.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws FileUploadException, IOException,
        AttachmentIsEmptyException, AuthorizationException {
    List<AttachmentResource> result = new ArrayList<>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
                        file.getSize(), false);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 23
Project: communote-server   File: AttachmentResourceHandler.java   Source Code and License 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws MaxLengthReachedException
 *             attachment size is to large
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AttachmentIsEmptyException
 *             Thrown, when the attachment is of zero size.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws MaxLengthReachedException, FileUploadException, IOException,
        AttachmentIsEmptyException, AuthorizationException {
    List<AttachmentResource> result = new ArrayList<AttachmentResource>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
                        file.getSize(), false);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 24
Project: communote-server   File: AttachmentResourceHandler.java   Source Code and License 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws MaxLengthReachedException
 *             attachment size is to large
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws MaxLengthReachedException, FileUploadException, IOException,
        AuthorizationException {
    List<AttachmentResource> result = new ArrayList<AttachmentResource>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
                        file.getSize(), false);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 25
Project: communote-server   File: AttachmentResourceHandler.java   Source Code and License 6 votes vote down vote up
/**
 * extracts attachments from the http request.
 *
 * @param httpRequest
 *            request containing attachments DefaultMultipartHttpServletRequest is supported
 * @param request
 *            {@link Request}
 * @return ids of extracted attachments
 * @throws MaxLengthReachedException
 *             attachment size is to large
 * @throws IOException
 *             throws exception if problems during attachments accessing occurred
 * @throws FileUploadException
 *             Exception.
 * @throws AuthorizationException
 *             in case there is no authenticated user
 */
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
        Request request) throws MaxLengthReachedException, FileUploadException, IOException,
        AuthorizationException {
    List<AttachmentResource> result = new ArrayList<AttachmentResource>();
    if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
        FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
        for (FileItem file : items) {
            if (!file.isFormField()) {
                AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
                        AttachmentStatus.UPLOADED);
                AttachmentResourceHelper.checkAttachmentSize(file);
                attachmentTo.setMetadata(new ContentMetadata());
                attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
                attachmentTo.getMetadata().setContentSize(file.getSize());
                result.add(persistAttachment(request, attachmentTo));
            }
        }
    }
    return result;
}
 
Example 26
Project: Poseidon   File: PoseidonServlet.java   Source Code and License 6 votes vote down vote up
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException {
    // If uploaded file size is more than 10KB, will be stored in disk
    DiskFileItemFactory factory = new DiskFileItemFactory();
    File repository = new File(FILE_UPLOAD_TMP_DIR);
    if (repository.exists()) {
        factory.setRepository(repository);
    }

    // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem
    // Apps also have to delete tmp file explicitly (if at all it went to disk)
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(httpRequest);
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    for (FileItem fileItem : fileItems) {
        String name = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            request.setAttribute(name, new String[] { fileItem.getString() });
        } else {
            request.setAttribute(name, fileItem);
        }
    }
}
 
Example 27
Project: ExilityCore-5.0.0   File: XLSHandler.java   Source Code and License 6 votes vote down vote up
/**
 * This method returns FileItem handler out of file field in HTTP request
 * 
 * @param req
 * @return FileItem
 * @throws IOException
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
public static FileItem getFileItem(HttpServletRequest req)
		throws IOException, FileUploadException {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	/*
	 * we can increase the in memory size to hold the file data but its
	 * inefficient so ignoring to factory.setSizeThreshold(20*1024);
	 */
	ServletFileUpload sFileUpload = new ServletFileUpload(factory);
	List<FileItem> items = sFileUpload.parseRequest(req);
	for (FileItem item : items) {
		if (!item.isFormField()) {
			return item;
		}
	}

	throw new FileUploadException("File field not found");

}
 
Example 28
Project: ExilityCore-5.0.0   File: HttpUtils.java   Source Code and License 6 votes vote down vote up
/***
 * Simplest way of handling files that are uploaded from form. Just put them
 * as name-value pair into service data. This is useful ONLY if the files
 * are reasonably small.
 * 
 * @param req
 * @param data
 *            data in which
 */
public void simpleExtract(HttpServletRequest req, ServiceData data) {
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	try {
		/**
		 * ServerFileUpload still deals with raw types. we have to have
		 * workaround that
		 */
		List<?> list = upload.parseRequest(req);
		if (list != null) {
			for (Object item : list) {
				if (item instanceof FileItem) {
					FileItem fileItem = (FileItem) item;
					data.addValue(fileItem.getFieldName(),
							fileItem.getString());
				} else {
					Spit.out("Servlet Upload retruned an item that is not a FileItem. Ignorinig that");
				}
			}
		}
	} catch (FileUploadException e) {
		Spit.out(e);
		data.addError("Error while parsing form data. " + e.getMessage());
	}
}
 
Example 29
Project: signalk-server-java   File: UploadProcessor.java   Source Code and License 6 votes vote down vote up
private void processUpload(Exchange exchange) throws Exception {
	logger.debug("Begin import:"+ exchange.getIn().getHeaders());
	if(exchange.getIn().getBody()!=null){
		logger.debug("Body class:"+ exchange.getIn().getBody().getClass());
	}else{
		logger.debug("Body class is null");
	}
	//logger.debug("Begin import:"+ exchange.getIn().getBody());
	MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
	InputRepresentation representation = new InputRepresentation((InputStream) exchange.getIn().getBody(), mediaType);
	logger.debug("Found MIME:"+ mediaType+", length:"+exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, Integer.class));
	//make a reply
	Json reply = Json.read("{\"files\": []}");
	Json files = reply.at("files");
	
	try {
		List<FileItem> items = new RestletFileUpload(new DiskFileItemFactory()).parseRepresentation(representation);
		logger.debug("Begin import files:"+items);
		for (FileItem item : items) {
			if (!item.isFormField()) {
				InputStream inputStream = item.getInputStream();
				
				Path destination = Paths.get(Util.getConfigProperty(STATIC_DIR)+Util.getConfigProperty(MAP_DIR)+item.getName());
				logger.debug("Save import file:"+destination);
				long len = Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING);
				Json f = Json.object();
				f.set("name",item.getName());
				f.set("size",len);
				files.add(f);
				install(destination);
			}
		}
	} catch (FileUploadException | IOException e) {
		logger.error(e.getMessage(),e);
	}
	exchange.getIn().setBody(reply);
}
 
Example 30
Project: OLE-INST   File: DocumentServlet.java   Source Code and License 6 votes vote down vote up
/**
 * @param request
 * @param response
 * @return docAction (add or delete)
 * @throws ServletException
 */
protected List<FileItem> getMultiPartFileItems(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    List<FileItem> items = null;
    try {
        if (isMultipart) {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            items = uploadHandler.parseRequest(request);
        }
    } catch (Exception ex) {
        LOG.error("Error in getting the Reading the File:", ex);
    }
    return items;
}
 
Example 31
Project: OLE-INST   File: DocumentServlet.java   Source Code and License 6 votes vote down vote up
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res)
        throws Exception {
    File targetDir = null;
    try {
        File file = null;
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
        Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
        while (items.hasNext()) {
            FileItem item = (FileItem) items.next();
            file = new File(FileUtils.getTempDirectory(), item.getName());
            item.write(file);
        }
        targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null);
        LOG.info("extractedBagFileLocation " + targetDir);
    } catch (IOException e) {
        LOG.error("IOException", e);
        sendResponseBag(res, e.getMessage(), "failure");
    } catch (FormatHelper.UnknownFormatException unknownFormatException) {
        LOG.error("unknownFormatException", unknownFormatException);
        sendResponseBag(res, unknownFormatException.getMessage(), "failure");
    }
    return compressUtils.getAllFilesList(targetDir);
}
 
Example 32
Project: OLE-INST   File: LicenseRestServlet.java   Source Code and License 6 votes vote down vote up
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res)
            throws Exception {
        File targetDir = null;
        try {
            File file = null;
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
            Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
            while (items.hasNext()) {
                FileItem item = (FileItem) items.next();
                file = new File(FileUtils.getTempDirectory(), item.getName());
                item.write(file);
            }
            targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), extractFilePath);
            LOG.info("extractedBagFileLocation " + targetDir);
        } catch (IOException e) {
            LOG.error("IOException", e);
//            sendResponseBag(res, e.getMessage(), "failure");
        } catch (FormatHelper.UnknownFormatException unknownFormatException) {
            LOG.error("unknownFormatException", unknownFormatException);
//            sendResponseBag(res, unknownFormatException.getMessage(), "failure");
        }
        return compressUtils.getAllFilesList(targetDir);
    }
 
Example 33
Project: sigmah   File: MultipartRequest.java   Source Code and License 6 votes vote down vote up
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException {
	if (!ServletFileUpload.isMultipartContent(request)) {
		LOGGER.error("Request content is not multipart.");
		throw new StatusServletException(Response.SC_PRECONDITION_FAILED);
	}
	
	final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request);
	while (iterator.hasNext()) {
		// Gets the first HTTP request element.
		final FileItemStream item = iterator.next();

		if (item.isFormField()) {
			final String value = Streams.asString(item.openStream(), "UTF-8");
			properties.put(item.getFieldName(), value);
			
		} else if(callback != null) {
			callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType());
		}
	}
}
 
Example 34
Project: socom   File: SocomRequest.java   Source Code and License 6 votes vote down vote up
public Map<String, FileItem> getMultipartContent() throws FileUploadException, IllegalAccessException {

		if (!ServletFileUpload.isMultipartContent(request))
			throw new IllegalAccessException();

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);

		Map<String, FileItem> result = new HashMap<String, FileItem>();

		@SuppressWarnings("unchecked")
		List<FileItem> items = upload.parseRequest(request);
		for (FileItem fi : items) {
			result.put(fi.getFieldName(), fi);
		}
		return result;
	}
 
Example 35
Project: FiWare-Template-Handler   File: TaskAttachmentAddResource.java   Source Code and License 6 votes vote down vote up
@Put
public AttachmentResponse addAttachment(Representation entity) {
  if(authenticate() == false) return null;
  
  String taskId = (String) getRequest().getAttributes().get("taskId");
  
  try {
    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = upload.parseRepresentation(entity);
    
    FileItem uploadItem = null;
    for (FileItem fileItem : items) {
      if(fileItem.getName() != null) {
        uploadItem = fileItem;
      }
    }
    
    String fileName = uploadItem.getName();
    
    Attachment attachment = ActivitiUtil.getTaskService().createAttachment(
        uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream());
    
    return new AttachmentResponse(attachment);
    
  } catch(Exception e) {
    throw new ActivitiException("Unable to add new attachment to task " + taskId);
  }
}
 
Example 36
Project: cim   File: HttpUpHandler.java   Source Code and License 6 votes vote down vote up
/** Process file upload */
private void processFileUpload(HttpRequest request, File uploadDir, String id) throws Exception {
    FileItemFactory factory = new DiskFileItemFactory(Config.THRESHOLD_UPLOAD, uploadDir);
    HttpServFileUpload fileUpload = new HttpServFileUpload(factory);
    fileUpload.setProgressListener(new MyProgressListener(id));

    List<FileItem> fileItems = fileUpload.parseRequest(new HttpServRequestContext(request));
    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();

        if (item.isFormField()) {
            processFormField(item);
        } else {
            processUploadedFile(item, uploadDir);
        }
    }
}
 
Example 37
Project: bird   File: UploadImage.java   Source Code and License 6 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	try {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		factory.setRepository(tempPathFile);
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
		List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
		Iterator<FileItem> i = items.iterator();
		while (i.hasNext()) {
		    FileItem fi = (FileItem) i.next();
		    String fileName = fi.getName();
		    if (fileName != null) {
		     File fullFile = new File(fi.getName());
		     File savedFile = new File(uploadPath, fullFile.getName());
		     fi.write(savedFile);
		    }
		 }

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 38
Project: Deskera-HRMS   File: FileUploadHandler.java   Source Code and License 6 votes vote down vote up
public HashMap getItems(HttpServletRequest request) throws ServiceException{
      HashMap itemMap=null;
try {
              String tempPath = System.getProperty("java.io.tmpdir");
              FileItemFactory factory = new DiskFileItemFactory(4096,new File(tempPath));
              ServletFileUpload upload = new ServletFileUpload(factory);
              upload.setSizeMax(1000000);
              List fileItems = upload.parseRequest(request);
              Iterator iter = fileItems.iterator();
              itemMap=new HashMap();
              while (iter.hasNext()) {
                  FileItem item = (FileItem) iter.next();

                  if (item.isFormField()) {
                      itemMap.put(item.getFieldName(), item.getString());
                  } else {
                      itemMap.put(item.getFieldName(), item);
                  }
              }
      } catch (Exception e) {
              e.printStackTrace();
              throw ServiceException.FAILURE("FileUploadHandler.getItems", e);
      }
      return itemMap;
  }
 
Example 39
Project: projectforge-webapp   File: UploadImageFileTemporary.java   Source Code and License 6 votes vote down vote up
/**
 * This function gets the fileItem from the form
 * 
 * @param items the list of fields sent to this servlet
 * @return the imgItem if not found it returns null
 */
private FileItem getImgFileItem(final HttpServletRequest request) throws FileUploadException
{
  // Create a factory for disk-based file items
  final FileItemFactory factory = new DiskFileItemFactory();
  // Create a new file upload handler
  final ServletFileUpload upload = new ServletFileUpload(factory);
  final List< ? > items = upload.parseRequest(request); // get the items sent by the form
  FileItem fileItem = null;
  final Iterator< ? > iter = items.iterator();
  // iterate over the items and if the required field is found break the loop
  while (iter.hasNext()) {
    fileItem = (FileItem) iter.next();
    if (fileItem.isFormField() == false) {
      break;
    }
  }
  return fileItem;
}
 
Example 40
Project: wizard   File: CodeMaintainServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public HSSFSheet uploadExcel(HttpServletRequest request)
		throws IOException, FileUploadException {

	ServletFileUpload fileupload = new ServletFileUpload(
			new DiskFileItemFactory());
	fileupload.setSizeMax(1024 * 1024 * 10);
	@SuppressWarnings("unchecked")
	List<FileItem> fileitems = fileupload.parseRequest(request);

	InputStream inputStream = null;

	for (FileItem fileitem : fileitems) {
		if (!fileitem.isFormField()) {
			inputStream = fileitem.getInputStream();
			break;
		}
	}

	HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
	return workbook.getSheetAt(0);

}
 
Example 41
Project: wizard   File: CodeMaintainServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public HSSFSheet uploadExcel(HttpServletRequest request)
		throws IOException, FileUploadException {

	ServletFileUpload fileupload = new ServletFileUpload(
			new DiskFileItemFactory());
	fileupload.setSizeMax(1024 * 1024 * 10);
	@SuppressWarnings("unchecked")
	List<FileItem> fileitems = fileupload.parseRequest(request);

	InputStream inputStream = null;

	for (FileItem fileitem : fileitems) {
		if (!fileitem.isFormField()) {
			inputStream = fileitem.getInputStream();
			break;
		}
	}

	HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
	return workbook.getSheetAt(0);

}
 
Example 42
Project: AndroidWebServ   File: HttpUpHandler.java   Source Code and License 6 votes vote down vote up
/** Process file upload */
private void processFileUpload(HttpRequest request, File uploadDir, String id) throws Exception {
    FileItemFactory factory = new DiskFileItemFactory(Config.THRESHOLD_UPLOAD, uploadDir);
    HttpServFileUpload fileUpload = new HttpServFileUpload(factory);
    fileUpload.setProgressListener(new MyProgressListener(id));

    List<FileItem> fileItems = fileUpload.parseRequest(new HttpServRequestContext(request));
    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();

        if (item.isFormField()) {
            processFormField(item);
        } else {
            processUploadedFile(item, uploadDir);
        }
    }
}
 
Example 43
Project: qb-archetype   File: RmUploadHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 功能: 从上传的request中得到普通字符值,一定要注意只能调用一次
 * @param request
 * @param fieldName
 * @return
 */
public static String getValueFromUploadForm(HttpServletRequest request, String fieldName) {
    String returnValue = null;
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        List lItems = sfu.parseRequest(request);
        java.util.Iterator iter = lItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (fieldName.equals(item.getFieldName())) {
                returnValue = item.getString();
                break;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return returnValue;
}
 
Example 44
Project: WorldOnline   File: ServletHelper.java   Source Code and License 6 votes vote down vote up
public static ParsedRequest getStringParametersMap(HttpServletRequest request) throws FileUploadException {
    HashMap<String, String> textMap = new HashMap<>();
    ParsedRequest parsedRequest = new ParsedRequest(textMap, null);
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> uploadItems = upload.parseRequest(request);
        for (FileItem item : uploadItems) {
            String fieldName = item.getFieldName();
            String value = item.getString();
            textMap.put(fieldName, value);
        }
    } catch (Exception e) {
        loggerFactory.error(e);
    }
    return parsedRequest;
}
 
Example 45
Project: WorldOnline   File: ServletHelper.java   Source Code and License 6 votes vote down vote up
public static ParsedRequest getParametersMap(HttpServletRequest request) throws FileUploadException {
    HashMap<String, String> textMap = new HashMap<>();
    HashMap<String, File> fileMap = new HashMap<>();
    ParsedRequest parsedRequest = new ParsedRequest(textMap, fileMap);
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> uploadItems = upload.parseRequest(request);
        for (FileItem item : uploadItems) {
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                String value = item.getString();
                textMap.put(fieldName, value);
            } else {
                String filename = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
                File file = new File(ServerConsts.tempFileStore + "/" + filename);
                FileHelper.saveToFile(fileContent, file);
                fileMap.put(fieldName, file);
            }
        }
    } catch (Exception e) {
        loggerFactory.error(e);
    }
    return parsedRequest;
}
 
Example 46
Project: metalcon   File: Server.java   Source Code and License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent arg0) {
	System.out.println("context initialized");
	this.start();

	final ServletContext context = arg0.getServletContext();
	context.setAttribute("server", this);

	// load status update types
	try {
		System.out.println("loading status update templates");
		StatusUpdateManager.loadStatusUpdateTemplates(
				context.getRealPath("/") + "WEB-INF/", this.config,
				this.graphDatabase);
		System.out.println("status update templates loaded");
	} catch (ParserConfigurationException | SAXException | IOException e) {
		System.err.println("failed to load status update templates!");
		e.printStackTrace();
	}

	final File tmpDir = (File) context
			.getAttribute("javax.servlet.context.tempdir");
	final DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(tmpDir);
	Create.setDiskFileItemFactory(factory);
}
 
Example 47
Project: bennu-renderers   File: RequestWrapperFilter.java   Source Code and License 6 votes vote down vote up
private void parseRequest(final HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException {
    final List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

    String characterEncoding = request.getCharacterEncoding();

    for (final FileItem item : fileItems) {
        if (item.isFormField()) {
            addParameter(item.getFieldName(),
                    characterEncoding != null ? item.getString(characterEncoding) : item.getString());
        } else {
            UploadedFile uploadedFile = new CommonsFile(item);

            String uploadFileName = uploadedFile.getName();
            String decodedName = null;
            if (uploadFileName != null && uploadFileName.length() > 0) {
                itemsMap.put(item.getFieldName(), uploadedFile);
                decodedName =
                        characterEncoding != null ? new String(uploadFileName.getBytes(), characterEncoding) : new String(
                                uploadFileName.getBytes());
            }

            addParameter(item.getFieldName(), decodedName);
        }
    }
}
 
Example 48
Project: javasec   File: RmUploadHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 功能: 从上传的request中得到普通字符值,一定要注意只能调用一次
 * @param request
 * @param fieldName
 * @return
 */
public static String getValueFromUploadForm(HttpServletRequest request, String fieldName) {
    String returnValue = null;
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        List lItems = sfu.parseRequest(request);
        java.util.Iterator iter = lItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (fieldName.equals(item.getFieldName())) {
                returnValue = item.getString();
                break;
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return returnValue;
}
 
Example 49
Project: OftenPorter   File: MultiPartParamSourceHandle.java   Source Code and License 5 votes vote down vote up
public MultiPartParamSourceHandle(MultiPartOption multiPartOption, boolean dealNormalPut)
{
    this.multiPartOption = multiPartOption;
    this.dealNormalPut = dealNormalPut;
    factory = new DiskFileItemFactory();
    if (multiPartOption.tempDir != null)
    {
        factory.setRepository(new File(multiPartOption.tempDir));
    }
    factory.setSizeThreshold(multiPartOption.cacheSize);
}
 
Example 50
Project: airsonic   File: AvatarUploadController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {

    String username = securityService.getCurrentUsername(request);

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }

    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);

    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;

        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();

            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }

    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult","model",map);
}
 
Example 51
Project: airsonic   File: ImportPlaylistController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
protected String handlePost(RedirectAttributes redirectAttributes,
                                       HttpServletRequest request
                                       ) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    try {
        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (Object o : items) {
                FileItem item = (FileItem) o;

                if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
                    if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
                        throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
                    }
                    String playlistName = FilenameUtils.getBaseName(item.getName());
                    String fileName = FilenameUtils.getName(item.getName());
                    String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName()));
                    String username = securityService.getCurrentUsername(request);
                    Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName,
                                                                       item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }

    redirectAttributes.addFlashAttribute("model", map);
    return "redirect:importPlaylist";
}
 
Example 52
Project: rainbow   File: UploadHandleServlet.java   Source Code and License 5 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            if (!ServletFileUpload.isMultipartContent(request))
            {
                return;
            }
            this.fileList = upload.parseRequest(request);
//            System.out.println(fileList.size());
            for (FileItem item : fileList)
            {
                if (item.isFormField())
                {
                    String value = item.getString("UTF-8");
//                  System.out.print(value);
                    names.add(value);
                } else
                {
                    String filename = item.getName();
                    if (filename == null) continue;
                    File newFile = new File(filename);
//            		System.out.println(newFile.getCanonicalPath());
//            		item.write(newFile);
                    this.names.add(newFile.getAbsolutePath().toString());
                    saveFile(item);
                }
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
 
Example 53
Project: nymph   File: ResolverUrlImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Map<String, String[]> multipartHandler() throws Exception {
	multipart = new Multipart();
	DiskFileItemFactory disk = new DiskFileItemFactory();
	ServletFileUpload servletFileUpload = new ServletFileUpload(disk);
	List<FileItem> items = servletFileUpload.parseRequest(wrapper.httpRequest());

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

	for (FileItem fileItem : items) {
		if (fileItem.isFormField()) {
			String fieldName = fileItem.getFieldName();
			String fieldVal = fileItem.getString("UTF-8");
			String[] param = params.get(fieldName);
			
			if (param != null) {
				String[] newArray = new String[param.length + 1];
				System.arraycopy(param, 0, newArray, 0, param.length);
				newArray[param.length] = fieldVal;
				param = newArray;
			} else {
				param = new String[]{fieldVal};
			}
			params.put(fieldName, param);
		} 
		else {
			multipart.addFiles(fileItem);
		}
	}
	return params;
}
 
Example 54
Project: DataStage   File: ExcelUploadService.java   Source Code and License 5 votes vote down vote up
@Override
public void configFileUpload( DiskFileItemFactory fileItemFactory,
        ServletFileUpload servletFileUpload )
{
    fileItemFactory.setSizeThreshold( BYTE_M * 10 );
    fileItemFactory.setRepository( new File( "D:\\appUploads" ) );
    servletFileUpload.setFileSizeMax( BYTE_M * 100 );
}
 
Example 55
Project: Android_Code_Arbiter   File: FileUploadCommon.java   Source Code and License 5 votes vote down vote up
public void handleFile(HttpServletRequest req) throws FileUploadException {
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    List<FileItem> fileItems = upload.parseRequest(req);

    for (FileItem item : fileItems) {
        System.out.println("Saving " + item.getName() + "...");
    }
}
 
Example 56
Project: validator-web   File: MultipartFormHttpMessageReader.java   Source Code and License 5 votes vote down vote up
@Override
public MultiValueMap<String, ?> read(Class<? extends MultiValueMap<String, ?>> clazz,
        HttpServletRequest request) throws IOException, HttpMessageNotReadableException {
    
    @SuppressWarnings("unchecked")
    MultiValueMap<String, Object> result = ServletUtils.extractUrlParams(request);
    
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    result.add(fileItem.getFieldName(), fileItem.getString(this.charset.name()));
                } else {
                    if (isImageMediaType(fileItem.getContentType())) {
                        result.add(fileItem.getFieldName(), new CommonsImageMultipartFile(fileItem));
                    } else {
                        result.add(fileItem.getFieldName(), new CommonsMultipartFile(fileItem));
                    }
                }
            }
        } catch (FileUploadException e) {
            logger.error("File upload failed", e);
        }
    }
    return result;
}
 
Example 57
Project: grain   File: FileHttpFilter.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化缓存文件夹
 */
public FileHttpFilter() {
	tempPath = HttpConfig.PROJECT_PATH + "/" + HttpConfig.PROJECT_NAME + "_TEMP";
	if (HttpConfig.log != null) {
		HttpConfig.log.info("缓存文件路径为:" + tempPath);
	}
	File file = new File(tempPath);
	if (!file.exists()) {
		file.mkdirs();
	}
	diskFileItemFactory = new DiskFileItemFactory();
	diskFileItemFactory.setSizeThreshold(1024);
	diskFileItemFactory.setRepository(file);
}
 
Example 58
Project: PCloud_Server_v3   File: UploadAction.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
	private void receiveFile(HttpServletRequest request, OnFileReceiveListener listener) throws Exception{
		
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 临时文件夹路径
		String repositoryPath = ConfigManager.getManager().FILE_TEMP_PATH;
		// 设定临时文件夹为repositoryPath
		File fileTempFolder = new File(repositoryPath);
		if(!fileTempFolder.exists())fileTempFolder.mkdirs();
		factory.setRepository(fileTempFolder);

		// 设定上传文件的阈值,如果上传文件大于1M,就可能在repository
		// 所代 表的文件夹中产生临时文件,否则直接在内存中进行处理
		factory.setSizeThreshold(1024 * 1024);

		// 创建一个ServletFileUpload对象
		ServletFileUpload uploader = new ServletFileUpload(factory);

			// 调用uploader中的parseRequest方法,可以获得请求中的相关内容,
			// 即一个FileItem类型的ArrayList。FileItem是在
			// org.apache.commons.fileupload中定义的,它可以代表一个文件,
			// 也可以代表一个普通的form field
			ArrayList<FileItem> list = (ArrayList<FileItem>) uploader.parseRequest(request);
			for (FileItem fileItem : list){
				if (!fileItem.isFormField()){ // 如果是文件
					String fileName = fileItem.getName() + UUID.randomUUID();
					// 将其中包含的内容写到指定目录下名为fileName的文件中
					File file = new File(ConfigManager.getManager().FILE_SAVE_PATH + File.separator + fileName);
					file.createNewFile();
//					System.out.println(file.getPath());
					fileItem.write(file);
					
					listener.onFinished(MD5.getMD5CodeByFile(file),fileName,file.length());
					break;//一次请求只接受一个文件
				}
			}
	}
 
Example 59
Project: tkhoon   File: UploadHelper.java   Source Code and License 5 votes vote down vote up
public static void init(ServletContext servletContext) {
    // 获取一个临时目录(使用 Tomcat 的 work 目录)
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    // 创建 FileUpload 对象
    fileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
    // 设置上传限制
    if (uploadLimit != 0) {
        fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024); // 单位为 M
        if (logger.isDebugEnabled()) {
            logger.debug("[Smart] limit of uploading: {}M", uploadLimit);
        }
    }
}
 
Example 60
Project: jw   File: FileUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @see http://www.oschina.net/code/snippet_698737_13402
 * @param request
 * @return
 * @throws IOException
 */
public static Map<String, Object> uploadFiles(HttpServlet servlet, HttpServletRequest request) {
    Map<String, Object> map = JwUtils.newHashMap();
    Map<String, String> fileMap = JwUtils.newHashMap();
    map.put("file", fileMap);

    DiskFileItemFactory factory = new DiskFileItemFactory();// 创建工厂
    factory.setSizeThreshold(1024 * 1024 * 30);// 设置最大缓冲区为30M

    // 设置缓冲区目录
    String savePath = servlet.getServletContext().getRealPath("/WEB-INF/temp");
    factory.setRepository(new File(savePath));

    FileUpload upload = new FileUpload(factory);// 获得上传解析器
    upload.setHeaderEncoding("UTF-8");// 解决上传文件名乱码
    
    try {
        String targetFolderPath = servlet.getServletContext().getRealPath("/WEB-INF/" + ConfigUtils.getProperty("web.files.upload.folder"));
        File targetFolder = new File(targetFolderPath);// 目标文件夹
        if(!targetFolder.exists()) {
            targetFolder.mkdir();
        }
        
        List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));// 解析请求体
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {// 判断是普通表单项还是文件上传项
                String name = fileItem.getFieldName();// 表单名
                String value = fileItem.getString("UTF-8");// 表单值
                map.put(name, value);
            } else {// 文件上传项
                String fileName = fileItem.getName();// 获取文件名
                if (StringUtils.isEmpty(fileName))// 判断是否上传了文件
                    continue;

                // 截取文件名
                int index = fileName.lastIndexOf("/");
                if (index > -1) {
                    fileName = fileName.substring(index);
                }

                // 检查文件是否允许上传
                index = fileName.lastIndexOf(".");
                if (index > -1 && index < fileName.length() - 1) {
                    String ext = fileName.substring(index + 1).toLowerCase();
                    if (!ConfigUtils.getString("web.files.upload.extension").contains(";" + ext + ";")) {
                        LOGGER.warn("The file {} is not allowed to upload.", fileName);
                        continue;
                    }
                }

                // 生成唯一文件名,保留原文件名
                String newFileName = UUID.randomUUID().toString();
                
                // 将文件内容写到服务器端
                String targetPath = targetFolderPath + "/" + newFileName;
                File targetFile = new File(targetPath);// 目标文件
                targetFile.createNewFile();
                fileItem.write(targetFile);

                fileItem.delete();// 删除临时文件
                fileMap.put(fileName, newFileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}