Java Code Examples for org.apache.commons.fileupload.FileItem

The following are top voted examples for showing how to use org.apache.commons.fileupload.FileItem. 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: scaffold   File: Uploader.java   Source Code and License 8 votes vote down vote up
/**
 * 文件上传处理类
 *
 * @return {@link UploadResult}
 * @throws Exception 抛出异常
 */
public UploadResult upload() throws Exception {
    boolean multipartContent = ServletFileUpload.isMultipartContent(request);
    if (!multipartContent) {
        throw new RuntimeException("上传表单enctype类型设置错误");
    }

    List<TextFormResult> textFormResultList = Lists.newArrayList();
    List<FileFormResult> fileFormResultList = Lists.newArrayList();

    List<FileItem> fileItems = upload.parseRequest(request);
    for (FileItem item : fileItems) {
        if (item.isFormField())
            textFormResultList.add(processFormField(item));
        else
            fileFormResultList.add(processUploadedFile(item));
    }
    return new UploadResult(textFormResultList, fileFormResultList);
}
 
Example 2
Project: DataStage   File: ExcelUploadService.java   Source Code and License 7 votes vote down vote up
@Override
public void handle( List<FileItem> fileItems )
{
    for ( FileItem file : fileItems )
    {
        byte[] fileName = file.getName().getBytes();

        try
        {
            String uploadName = new String( fileName, "utf-8" );
            System.out.println( uploadName );

            File writeFile = new File( "D:\\" + uploadName );

            file.write( writeFile );

        } catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
 
Example 3
Project: hermes   File: PartnershipPageletAdaptor.java   Source Code and License 7 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
Example 4
Project: iBase4J-Common   File: ExcelReaderUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取Excel数据,返回List
 * 
 * @param sheetNumber
 *            读取工作表的下标(从1开始).可有可无,默认读取所有表单.
 */
public static final List<String[]> excelToArrayList(String fileName, FileItem fileItem, int... sheetNumber)
    throws Exception {
    List<String[]> resultList = null;
    InputStream is = null;
    try {
        is = fileItem.getInputStream();
        resultList = excelToArrayList(fileName, is, sheetNumber);
    } catch (Exception e) {
        throw e;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return resultList;
}
 
Example 5
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 6
Project: automat   File: ExcelReaderUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取Excel数据,返回List<String[]>
 * 
 * @param sheetNumber
 *            读取工作表的下标(从1开始).可有可无,默认读取所有表单.
 */
public static final List<String[]> excelToArrayList(String fileName, FileItem fileItem, int... sheetNumber)
		throws Exception {
	List<String[]> resultList = null;
	InputStream is = null;
	try {
		is = fileItem.getInputStream();
		resultList = excelToArrayList(fileName, is, sheetNumber);
	} catch (Exception e) {
		throw e;
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return resultList;
}
 
Example 7
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 8
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 9
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 10
Project: iBase4J   File: ExcelReaderUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取Excel数据,返回List<String[]>
 * 
 * @param sheetNumber
 *            读取工作表的下标(从1开始).可有可无,默认读取所有表单.
 */
public static final List<String[]> excelToArrayList(String fileName, FileItem fileItem, int... sheetNumber)
		throws Exception {
	List<String[]> resultList = null;
	InputStream is = null;
	try {
		is = fileItem.getInputStream();
		resultList = excelToArrayList(fileName, is, sheetNumber);
	} catch (Exception e) {
		throw e;
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return resultList;
}
 
Example 11
Project: JAVA-   File: ExcelReaderUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取Excel数据,返回List<String[]>
 * 
 * @param sheetNumber
 *            读取工作表的下标(从1开始).可有可无,默认读取所有表单.
 */
public static final List<String[]> excelToArrayList(String fileName, FileItem fileItem, int... sheetNumber)
		throws Exception {
	List<String[]> resultList = null;
	InputStream is = null;
	try {
		is = fileItem.getInputStream();
		resultList = excelToArrayList(fileName, is, sheetNumber);
	} catch (Exception e) {
		throw e;
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return resultList;
}
 
Example 12
Project: tephra   File: UploadHelperImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void upload(HttpServletRequest request, HttpServletResponse response) {
    try {
        serviceHelper.setCors(request, response);
        OutputStream outputStream = serviceHelper.setContext(request, response, URI);
        List<UploadReader> readers = new ArrayList<>();
        for (FileItem item : getUpload(request).parseRequest(request))
            if (!item.isFormField())
                readers.add(new HttpUploadReader(item));
        outputStream.write(json.toBytes(uploadService.uploads(readers)));
        outputStream.flush();
        outputStream.close();
    } catch (Throwable e) {
        logger.warn(e, "处理文件上传时发生异常!");
    } finally {
        closables.close();
    }
}
 
Example 13
Project: dataforms   File: FolderFileStore.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <pre>
 * 一時ファイルの保存処理ですが、性能を考慮し本来のフォルダに保存します。
 * </pre>
 */
@Override
public File makeTempFromFileItem(final FileItem fileItem) throws Exception {
	this.fileName = FileUtil.getFileName(fileItem.getName());

	File file = this.makeUniqFile();
	FileOutputStream os = new FileOutputStream(file);
	try {
		InputStream is = fileItem.getInputStream();
		try {
			FileUtil.copyStream(is, os);
		} finally {
			is.close();
		}
	} finally {
		os.close();
	}
	return file;
}
 
Example 14
Project: melon   File: UploadUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 文件上传
 *
 * @param request
 * @return infos info[0] 验证文件域返回错误信息 info[1] 上传文件错误信息 info[2] savePath
 * info[3] saveUrl info[4] fileUrl
 */
@SuppressWarnings("unchecked")
public String[] uploadFile(HttpServletRequest request) {
    String[] infos = new String[5];
    // 验证
    infos[0] = this.validateFields(request);
    // 初始化表单元素
    Map<String, Object> fieldsMap = new HashMap<String, Object>();
    if (infos[0].equals("true")) {
        fieldsMap = this.initFields(request);
    }
    // 上传
    List<FileItem> fiList = (List<FileItem>) fieldsMap.get(UploadUtils.FILE_FIELDS);
    if (fiList != null) {
        for (FileItem item : fiList) {
            infos[1] = this.saveFile(item);
        }
        infos[2] = savePath;
        infos[3] = saveUrl;
        infos[4] = fileUrl;
    }
    return infos;
}
 
Example 15
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 16
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 17
Project: dataforms   File: BlobFileStore.java   Source Code and License 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 * <pre>
	 * BLOBに保存するためヘッダ情報 + ファイル本体の形式の一時ファイルを作成します。
	 * </pre>
	 */
	@Override
	protected File makeTempFromFileItem(final FileItem fileItem) throws Exception {
//		log.error("makeTempFromFileItem", new Exception());
		String fileName = FileUtil.getFileName(fileItem.getName());
		long length = fileItem.getSize();
		File file = null;
		InputStream is = fileItem.getInputStream();
		try {
			file = this.makeBlobTempFile(fileName, length, is);
		} finally {
			is.close();
		}
//		this.tempFile = file;
		return file;
	}
 
Example 18
Project: openbravo-brazil   File: VariablesBase.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieve a parameter passed to the servlet as part of a multi part content.
 * 
 * @param parameter
 *          the name of the parameter to be retrieved
 * @param requestFilter
 *          filter used to validate the input against list of allowed inputs
 * @return String containing the value of the parameter. Empty string if the content is not
 *         multipart or the parameter is not found.
 */
public String getMultiParameter(String parameter, RequestFilter requestFilter) {
  if (!isMultipart || items == null)
    return "";
  Iterator<FileItem> iter = items.iterator();
  while (iter.hasNext()) {
    FileItem item = iter.next();
    if (item.isFormField() && item.getFieldName().equals(parameter)) {
      try {
        String value = item.getString("UTF-8");
        filterRequest(requestFilter, value);
        return value;
      } catch (Exception ex) {
        ex.printStackTrace();
        return "";
      }
    }
  }
  return "";
}
 
Example 19
Project: openbravo-brazil   File: VariablesBase.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieve a set of values belonging to a parameter passed to the servlet as part of a multi part
 * content.
 * 
 * @param parameter
 *          The name of the parameter to be retrieved.
 * @param requestFilter
 *          filter used to validate the input against list of allowed inputs
 * @return String array containing the values of the parameter. Empty string if the content is not
 *         multipart.
 */
public String[] getMultiParameters(String parameter, RequestFilter requestFilter) {
  if (!isMultipart || items == null)
    return null;
  Iterator<FileItem> iter = items.iterator();
  Vector<String> result = new Vector<String>();
  while (iter.hasNext()) {
    FileItem item = iter.next();
    if (item.isFormField() && item.getFieldName().equals(parameter)) {
      try {
        String value = item.getString("UTF-8");
        filterRequest(requestFilter, value);
        result.addElement(value);
      } catch (Exception ex) {
      }
    }
  }
  String[] strResult = new String[result.size()];
  result.copyInto(strResult);
  return strResult;
}
 
Example 20
Project: giiwa   File: upload.java   Source Code and License 6 votes vote down vote up
@Override
public void onPost() {

	JSON jo = new JSON();
	User me = this.getUser();

	if (me != null) {
		// String access = Module.home.get("upload.require.access");

		FileItem file = this.getFile("file");
		store(me.getId(), file, jo);

	} else {
		this.set(X.ERROR, HttpServletResponse.SC_UNAUTHORIZED);
		jo.put(X.MESSAGE, lang.get("login.required"));
	}

	// /**
	// * test
	// */
	// jo.put("error", "error");
	this.response(jo);

}
 
Example 21
Project: simbest-cores   File: CustomMultipartResolver.java   Source Code and License 6 votes vote down vote up
public List<FileItem> checkContentType(HttpServletRequest request, String encoding){
    if(null != fileTypes && fileTypes.size() > 0){
        FileUpload fileUpload = prepareFileUpload(encoding);
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            for (FileItem item : fileItems) {
                if(!item.isFormField()) { //必须是文件
                    log.debug("client want to upload file with name: " + item.getName());
                    log.debug("client want to upload file with type: " + item.getContentType());
                    if (!fileTypes.contains(AppFileUtils.getFileExtByName(item.getName()))) {
                        for(String fileType : fileTypes){
                            log.error("Allowd fileType is: "+fileType);
                        }
                        throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur, client upload type is: "+AppFileUtils.getFileExtByName(item.getName()));
                    }
                }
            }
            return fileItems;
        } catch (FileUploadException e) {
            throw new NotAllowUploadFileTypeException("Not allow upload file type exception occur... \r\n" + e.getMessage());
        }
    }
    return null;
}
 
Example 22
Project: bisis-v4   File: FileStorage.java   Source Code and License 6 votes vote down vote up
public static void store(DocFile doc, FileItem fileItem) {
  String fullPath = getFullPath(doc);
  File file = new File(fullPath);
  if (file.isFile()) {
    log.warn("File " + fullPath + " exists: will be overwritten!");
  }
  File dir = file.getParentFile();
  if (!dir.exists()) {
    dir.mkdirs();
    log.info("Creating directory " + dir.getAbsolutePath());
  }
  try {
  	 fileItem.write(file);
  } catch (Exception ex) {
    log.fatal(ex);
  }
}
 
Example 23
Project: hermes   File: PartnershipPageletAdaptor.java   Source Code and License 6 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
    throws FileUploadException, IOException {
	Hashtable ht = new Hashtable();
	DiskFileUpload upload = new DiskFileUpload();
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
	    FileItem item = (FileItem) iter.next();
	    if (item.isFormField()) {
	        ht.put(item.getFieldName(), item.getString());
	    } else {
	        if (item.getName().equals("")) {
	            //ht.put(item.getFieldName(), null);
	        } else if (item.getSize() == 0) {
	            //ht.put(item.getFieldName(), null);
	        } else {
	            ht.put(item.getFieldName(), item.getInputStream());
	        }
	    }
	}
	return ht;
}
 
Example 24
Project: hermes   File: PartnershipPageletAdaptor.java   Source Code and License 6 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
Example 25
Project: hermes   File: PartnershipPageletAdaptor.java   Source Code and License 6 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
Example 26
Project: scaffold   File: Uploader.java   Source Code and License 6 votes vote down vote up
/**
 * 解析上传域
 *
 * @param item 文件对象
 * @return {@link FileFormResult}
 * @throws IOException IO异常
 */
private FileFormResult processUploadedFile(FileItem item) throws IOException {
    String name = item.getName();
    String fileSuffix = FilenameUtils.getExtension(name);
    if (CollectionUtils.isNotEmpty(allowedSuffixList) && !allowedSuffixList.contains(fileSuffix)) {
        throw new NotAllowedUploadException(String.format("上传文件格式不正确,fileName=%s,allowedSuffixList=%s",
                name, allowedSuffixList));
    }
    FileFormResult file = new FileFormResult();
    file.setFieldName(item.getFieldName());
    file.setFileName(name);
    file.setContentType(item.getContentType());
    file.setSizeInBytes(item.getSize());

    //如果未设置上传路径,直接保存到项目根目录
    if (Strings.isNullOrEmpty(baseDir)) {
        baseDir = request.getRealPath("/");
    }
    File relativePath = new File(SEPARATOR + DateFormatUtils.format(new Date(), "yyyyMMdd") + file.getFileName());
    FileCopyUtils.copy(item.getInputStream(), new FileOutputStream(relativePath));
    file.setSaveRelativePath(relativePath.getAbsolutePath());
    return file;
}
 
Example 27
Project: sonar-scanner-maven   File: CommonsMultipartRequestHandler.java   Source Code and License 6 votes vote down vote up
/**
 * <p> Adds a file parameter to the set of file parameters for this
 * request and also to the list of all parameters. </p>
 *
 * @param item The file item for the parameter to add.
 */
protected void addFileParameter(FileItem item) {
    FormFile formFile = new CommonsFormFile(item);

    String name = item.getFieldName();
    if (elementsFile.containsKey(name)) {
        Object o = elementsFile.get(name);
        if (o instanceof List) {
            ((List)o).add(formFile);
        } else {
            List list = new ArrayList();
            list.add((FormFile)o);
            list.add(formFile);
            elementsFile.put(name, list);
            elementsAll.put(name, list);
        }
    } else {
        elementsFile.put(name, formFile);
        elementsAll.put(name, formFile);
    }
}
 
Example 28
Project: dataforms   File: RestoreForm.java   Source Code and License 6 votes vote down vote up
/**
 * バックアップファイルを解凍します。
 * @param fileItem バックアップファイル。
 * @return 展開されたディレクトリのパス。
 * @throws Exception 例外。
 */
public String unpackRestoreFile(final FileItem fileItem) throws Exception {
	InputStream is = fileItem.getInputStream();
	String ret = null;
	try {
		File bkdir = new File(DataFormsServlet.getTempDir() + "/restore");
		if (!bkdir.exists()) {
			bkdir.mkdirs();
		}
		Path backup = FileUtil.createTempDirectory(bkdir.getAbsolutePath(), "restore");
		FileUtil.unpackZipFile(is, backup.toString());
		ret = backup.toString();
	} finally {
		is.close();
	}
	return ret;
}
 
Example 29
Project: struts2   File: JakartaMultiPartRequest.java   Source Code and License 6 votes vote down vote up
protected void processFileField(FileItem item) {
    LOG.debug("Item is a file upload");

    // Skip file uploads that don't have a file name - meaning that no file was selected.
    if (item.getName() == null || item.getName().trim().length() < 1) {
        LOG.debug("No file has been uploaded for the field: {}", item.getFieldName());
        return;
    }

    List<FileItem> values;
    if (files.get(item.getFieldName()) != null) {
        values = files.get(item.getFieldName());
    } else {
        values = new ArrayList<>();
    }

    values.add(item);
    files.put(item.getFieldName(), values);
}
 
Example 30
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 31
Project: dataforms   File: RestoreForm.java   Source Code and License 6 votes vote down vote up
/**
 * リストアを行います。
 * @param p パラメータ。
 * @return 処理結果。
 * @throws Exception 例外。
 */
@WebMethod
public Response restore(final Map<String, Object> p) throws Exception {
	this.methodStartLog(log, p);
	Response resp = null;
	List<ValidationError> list = this.validate(p);
	if (list.size() == 0) {
		FileItem fi = (FileItem) p.get("backupFile");
		String path = this.unpackRestoreFile(fi);
		TableManagerDao dao = new TableManagerDao(this);
		List<String> flist = FileUtil.getFileList(path);
		for (String fn: flist) {
			if (Pattern.matches(".*\\.data\\.json$", fn)) {
				log.debug("fn=" + fn);
				String classname = fn.substring(path.length() + 1).replaceAll("[\\\\/]", ".").replaceAll("\\.data\\.json$", "");
				log.debug("classname=" + classname);
				dao.importData(classname, path);
			}
		}
		resp = new JsonResponse(JsonResponse.SUCCESS, MessagesUtil.getMessage(this.getPage(), "message.restored"));
	} else {
		resp = new JsonResponse(JsonResponse.INVALID, list);
	}
	this.methodFinishLog(log, resp);
	return resp;
}
 
Example 32
Project: struts2   File: JakartaMultiPartRequest.java   Source Code and License 6 votes vote down vote up
public void cleanUp() {
    Set<String> names = files.keySet();
    for (String name : names) {
        List<FileItem> items = files.get(name);
        for (FileItem item : items) {
            if (LOG.isDebugEnabled()) {
                String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file",
                        Locale.ENGLISH, "no.message.found", new Object[]{name, item});
                LOG.debug(msg);
            }
            if (!item.isInMemory()) {
                item.delete();
            }
        }
    }
}
 
Example 33
Project: helicalinsight   File: MultipartFilter.java   Source Code and License 6 votes vote down vote up
/**
 * Process multipart request item as regular form field. The name and value
 * of each regular form field will be added to the given parameterMap.
 *
 * @param formField    The form field to be processed.
 * @param parameterMap The parameterMap to be used for the HttpServletRequest.
 */
private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {
    String name = formField.getFieldName();
    String value = formField.getString();
    String[] values = parameterMap.get(name);

    if (values == null) {
        // Not in parameter map yet, so add as new value.
        parameterMap.put(name, new String[]{value});
    } else {
        // Multiple field values, so add new value to existing array.
        int length = values.length;
        String[] newValues = new String[length + 1];
        System.arraycopy(values, 0, newValues, 0, length);
        newValues[length] = value;
        parameterMap.put(name, newValues);
    }
}
 
Example 34
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 35
Project: azkaban   File: MultipartParser.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Map<String, Object> parseMultipart(HttpServletRequest request)
    throws IOException, ServletException {
  ServletFileUpload upload = new ServletFileUpload(_uploadItemFactory);
  List<FileItem> items = null;
  try {
    items = upload.parseRequest(request);
  } catch (FileUploadException e) {
    throw new ServletException(e);
  }

  Map<String, Object> params = new HashMap<String, Object>();
  for (FileItem item : items) {
    if (item.isFormField())
      params.put(item.getFieldName(), item.getString());
    else
      params.put(item.getFieldName(), item);
  }
  return params;
}
 
Example 36
Project: tern   File: FileData.java   Source Code and License 6 votes vote down vote up
FileData(FileItem item)
{
	this.fileName = item.getName();
	this.type = item.getContentType();
	this.data = item.get();
	
	if(fileName != null)
	{
		int i = fileName.lastIndexOf("/");
		if(i>0)
		{
			fileName = fileName.substring(i+1);
		}
		else
		{
			i = fileName.lastIndexOf("\\");
			if(i>0)
    		{
    			fileName = fileName.substring(i+1);
    		}
		}
	}
	
	this.item = item;
}
 
Example 37
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 38
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 39
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 40
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 41
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 42
Project: convertigo-engine   File: Install.java   Source Code and License 5 votes vote down vote up
@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {		
	File fullFile = new File(item.getName());
	String certifNameExtension=fullFile.getName().replaceFirst(".*\\.", ".");
	if(CertificateManager.isCertificateExtension(certifNameExtension)){
		File savedFile = new File(getRepository(), fullFile.getName());
		item.write(savedFile);			
		ServiceUtils.addMessage(document, document.getDocumentElement(), "The certificate \""+fullFile.getName()+"\" has been successfully uploaded", "message", false);
	}
	else{
		ServiceUtils.addMessage(document, document.getDocumentElement(), "The extension \""+certifNameExtension+"\" isn't valid", "error", false);
	}
}
 
Example 43
Project: lams   File: CommonsMultipartRequestHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Adds a file parameter to the set of file parameters for this request
 * and also to the list of all parameters.
 *
 * @param item    The file item for the parameter to add.
 */
protected void addFileParameter(FileItem item) {
    FormFile formFile = new CommonsFormFile(item);

    elementsFile.put(item.getFieldName(), formFile);
    elementsAll.put(item.getFieldName(), formFile);
}
 
Example 44
Project: unitimes   File: ScriptExecution.java   Source Code and License 5 votes vote down vote up
public ScriptExecution(ExecuteScriptRpcRequest request, SessionContext context) {
	super(context.getUser());
	iRequest = request;
	
	Script script = ScriptDAO.getInstance().get(request.getScriptId());
	if (script.getPermission() != null)
		context.checkPermission(Right.valueOf(script.getPermission().replace(" ", "")));
	
	for (ScriptParameter parameter: script.getParameters())
		if ("file".equals(parameter.getType()))
			iFile = (FileItem)context.getAttribute(UploadServlet.SESSION_LAST_FILE);
}
 
Example 45
Project: unitimes   File: FileUploadBackend.java   Source Code and License 5 votes vote down vote up
@Override
public FileUploadRpcResponse execute(FileUploadRpcRequest request, SessionContext helper) {
	if (request.isReset()) {
		helper.setAttribute(UploadServlet.SESSION_LAST_FILE, null);
		return new FileUploadRpcResponse();
	} else {
		FileItem file = (FileItem)helper.getAttribute(UploadServlet.SESSION_LAST_FILE);
		return (file == null ? new FileUploadRpcResponse() : new FileUploadRpcResponse(file.getName()));
	}
}
 
Example 46
Project: nymph   File: Multipart.java   Source Code and License 5 votes vote down vote up
public void addFiles(FileItem fileItem) {
	try {
		fileInfo.put(fileItem.getFieldName(), 
				new FileInf(fileItem.getName(), fileItem.getInputStream()));
	} catch (Exception e) {
		LOOGER.error(null, e);
	}
}
 
Example 47
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 48
Project: gitplex-mit   File: DropzoneField.java   Source Code and License 5 votes vote down vote up
@Override
public void convertInput() {
	if (fileItems.isEmpty()) {
		setConvertedInput(null);
	} else {
		Collection<FileUpload> uploads = new ArrayList<>();
		for (FileItem fileItem: fileItems) {
			uploads.add(new FileUpload(fileItem));
		}
		setConvertedInput(uploads);
	}
}
 
Example 49
Project: satisfy   File: FileUploadServlet.java   Source Code and License 5 votes vote down vote up
private void processFileItems(List<FileItem> fileItems) throws Exception {
    if (isExists(fileItems)) {
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {
                saveFileItem(item);
            }
        }
    }
}
 
Example 50
Project: satisfy   File: FileUploadServlet.java   Source Code and License 5 votes vote down vote up
private void saveFileItem(FileItem item) throws Exception {
    String[] fileNameParts = new File(item.getName()).getName().split("\\" +
            ".");
    String suffix = "." + fileNameParts[1];
    String prefix = fileNameParts[0];
    File storeFile = File.createTempFile(prefix, suffix);
    item.write(storeFile);
    log.info("UPLOADED FILE IS - " + storeFile.getAbsolutePath());
}
 
Example 51
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 52
Project: yadaframework   File: YadaCommonsMultipartResolver.java   Source Code and License 5 votes vote down vote up
@Override
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
	try {
		return super.parseRequest(request);
	} catch (MaxUploadSizeExceededException e) {
		request.setAttribute(MAX_UPLOAD_SIZE_EXCEEDED_KEY, e);
		return parseFileItems(Collections.<FileItem> emptyList(), null);
	}
}
 
Example 53
Project: validator-web   File: CommonsImageMultipartFile.java   Source Code and License 5 votes vote down vote up
protected BufferedImage readImage(FileItem file) throws IOException {
    InputStream in = file.getInputStream();
    if (in == null) {
        return null;
    }
    return ImageIO.read(in);
}
 
Example 54
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 55
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 56
Project: tephra   File: HttpUploadReader.java   Source Code and License 5 votes vote down vote up
HttpUploadReader(FileItem item) throws IOException {
    this.item = item;
    fieldName = item.getFieldName();
    fileName = item.getName();
    contentType = item.getContentType();
    size = item.getSize();
    inputStream = item.getInputStream();
}
 
Example 57
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;
}
 
Example 58
Project: AndServer   File: UploadHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Parse file and save.
 *
 * @param request       request.
 * @param saveDirectory save directory.
 * @throws Exception may be.
 */
private void processFileUpload(HttpRequest request, File saveDirectory) throws Exception {
    FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, saveDirectory);
    HttpFileUpload fileUpload = new HttpFileUpload(factory);

    // Set upload process listener.
    // fileUpload.setProgressListener(new ProgressListener(){...});

    List<FileItem> fileItems = fileUpload.parseRequest(new HttpUploadContext((HttpEntityEnclosingRequest) request));

    for (FileItem fileItem : fileItems) {
        if (!fileItem.isFormField()) { // File param.
            // Attribute.
            // fileItem.getContentType();
            // fileItem.getFieldName();
            // fileItem.getName();
            // fileItem.getSize();
            // fileItem.getString();

            File uploadedFile = new File(saveDirectory, fileItem.getName());
            // 把流写到文件上。
            fileItem.write(uploadedFile);
        } else { // General param.
            String key = fileItem.getName();
            String value = fileItem.getString();
        }
    }
}
 
Example 59
Project: dataforms   File: FileField.java   Source Code and License 5 votes vote down vote up
@Override
public void setClientValue(final Object v) {
	try {
		FileObject value = this.newFileObject();
		if (v instanceof FileItem) {
			value.copy(this.newFileStore().convertToFileObject((FileItem) v));
		}
		this.setValueObject(value);
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		throw new ApplicationError(e);
	}
}
 
Example 60
Project: dataforms   File: DataFormsServlet.java   Source Code and License 5 votes vote down vote up
/**
 * File Uploadがある場合のパラメータ解析を行います。
 * @param req HTTPリクエスト。
 * @return パラメータ解析結果。
 * @throws Exception 例外。
 */
private Map<String, Object> getParameterMapForMultipart(final HttpServletRequest req) throws Exception {
	Map<String, Object> map = new HashMap<String, Object>();
	DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(new File(tempDir)); //一時的に保存する際のディレクトリ
	ServletFileUpload upload = new ServletFileUpload(factory);
	upload.setHeaderEncoding(encoding);
	@SuppressWarnings("unchecked")
	List<FileItem> list = upload.parseRequest(req);
	for (FileItem item : list) {
		String key = item.getFieldName();
		if (key != null) {
			if (item.isFormField()) {
				String value = item.getString(encoding);
				this.addParamMap(map, key, value);
			} else {
				String filename = item.getName();
				if (StringUtil.isBlank(filename)) {
					map.put(key, null);
				} else {
					map.put(key, item);
				}
			}
		}
	}
	return map;
}