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

The following examples show how to use org.apache.commons.fileupload.disk.DiskFileItemFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AdapterPortlet.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Handle multipart form.
 *
 * @param request
 *            the request
 * @param requestContext
 *            the request context
 *
 * @throws Exception
 *             the exception
 */
private void handleMultipartForm(ActionRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

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

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

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString();
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example #2
Source File: ActionRequestReader.java    From journaldev with MIT License 6 votes vote down vote up
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
	// Handle default MIME type request
	if(request.getContentType().equals("application/x-www-form-urlencoded")){
		String message = request.getParameter("message");
		System.out.println(message);
	}
	// Handle multipart request
	else if(request.getContentType().contains("multipart/form-data")){
		// Create FileItemFactory
		FileItemFactory factory = new DiskFileItemFactory();
		// Create PortletFileUpload instance
		PortletFileUpload fileUpload = new PortletFileUpload(factory);
		try {
			// Instead of parsing the request ourselves, let Apache PortletFileUpload do that
			List<FileItem> files = fileUpload.parseRequest(request);
			// Iterate over files
			for(FileItem item : files){
				// Print out some of information
				System.out.println("File Uploaded Name Is : "+item.getName()+" , Its Size Is :: "+item.getSize());
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		System.out.println(response.encodeURL("/index.html"));
	}
}
 
Example #3
Source File: HttpUpHandler.java    From AndroidWebServ with Apache License 2.0 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 #4
Source File: TestFastDfs.java    From uccn with Apache License 2.0 6 votes vote down vote up
private static FileItem createFileItem(String filePath) {
    FileItemFactory factory = new DiskFileItemFactory(16, null);
    String textFieldName = "textField";
    int num = filePath.lastIndexOf(".");
    String extFile = filePath.substring(num);
    FileItem item = factory.createItem(textFieldName, "text/plain", true,
            "MyFileName" + extFile);
    File newfile = new File(filePath);
    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    try {
        FileInputStream fis = new FileInputStream(newfile);
        OutputStream os = item.getOutputStream();
        while ((bytesRead = fis.read(buffer, 0, 8192))
                != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return item;
}
 
Example #5
Source File: ParseUploadUtil.java    From S-mall-servlet with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * @param request Servlet请求
 * @param params 一个预备的键值表储存非文件流的参数Map
 * @return 上传的文件流
 */
public static InputStream parseUpload(HttpServletRequest request, Map<String,String> params){
    InputStream is = null;
    try{
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        factory.setSizeThreshold(10*1024*1024);
        List<FileItem> items= upload.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                is = item.getInputStream();
            } else {
                String paramName = item.getFieldName();
                String paramValue = item.getString();
                paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
                params.put(paramName, paramValue);
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return is;
}
 
Example #6
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) 
	throws Exception{
	SourceBean serviceRequest = requestContext.getServiceRequest();
	
	// Create a factory for disk-based file items
	FileItemFactory factory = new DiskFileItemFactory();
	
    // Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            serviceRequest.setAttribute(name, value);
        } else {
            processFileField(item, requestContext);
        }
    }
}
 
Example #7
Source File: Multipart_mysql.java    From openrasp-testcases with MIT License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String id = null;
        if (req.getMethod().equals("POST")) {
            if (ServletFileUpload.isMultipartContent(req)) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(req);
                for (FileItem item : items) {
                    if (item.isFormField() && item.getFieldName().equals("id")) {
                        id = item.getString();
                        break;
                    }
                }
            }
        }
        if (id == null) {
            id = "1";
        }
        String result = Mysql.runQuery(id);
        resp.getWriter().println(result);
    } catch (Exception e) {
        resp.getWriter().println(e);
    }
}
 
Example #8
Source File: AdapterPortlet.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void handleMultipartForm(ActionRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

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

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

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString();
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example #9
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Handle multipart form.
 * 
 * @param request        the request
 * @param requestContext the request context
 * 
 * @throws Exception the exception
 */
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

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

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

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString(request.getCharacterEncoding());
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example #10
Source File: HttpUtilities.java    From odo with Apache License 2.0 6 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 #11
Source File: AnalysisPreviewFile.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private FileItem handleMultipartForm(HttpServletRequest request) throws Exception {

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

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

		// Parse the request
		List fileItems = upload.parseRequest(request);
		Iterator iter = fileItems.iterator();

		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
			} else {
				return item;
			}
		}
		return null;
	}
 
Example #12
Source File: FrameServletHandler.java    From urule with Apache License 2.0 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 #13
Source File: PackageServletHandler.java    From urule with Apache License 2.0 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 #14
Source File: UploadDatasetFileResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private FileItem handleMultipartForm(HttpServletRequest request) throws Exception {

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

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

		// Parse the request
		List fileItems = upload.parseRequest(request);
		Iterator iter = fileItems.iterator();

		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
			} else {
				return item;
			}
		}
		return null;
	}
 
Example #15
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Handle multipart form.
 * 
 * @param request        the request
 * @param requestContext the request context
 * 
 * @throws Exception the exception
 */
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

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

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

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString(request.getCharacterEncoding());
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example #16
Source File: AbstractFileUploadExecutor.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
protected List parseRequest(ServletRequestContext requestContext) throws FileUploadException {
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    return upload.parseRequest(requestContext);
}
 
Example #17
Source File: AvatarUploadController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping
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<FileItem> items = upload.parseRequest(request);

    // Look for file items.
    for (FileItem item : items) {
        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 #18
Source File: MultipartFormHttpMessageReader.java    From validator-web with Apache License 2.0 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 #19
Source File: Uploader.java    From jeecg with Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example #20
Source File: SecurityUIUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static List parseRequest(ServletRequestContext requestContext)
        throws FileUploadException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    return upload.parseRequest(requestContext);
}
 
Example #21
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception {
	SourceBean serviceRequest = requestContext.getServiceRequest();

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

	// This is done to make upload work in Unix solaris
	// ((DiskFileItemFactory)factory).setSizeThreshold(5242880);

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

	// upload.setFileSizeMax(5242880);
	// upload.setSizeMax(5242880);

	// Parse the request
	List fileItems = upload.parseRequest(request);
	Iterator iter = fileItems.iterator();
	while (iter.hasNext()) {
		FileItem item = (FileItem) iter.next();

		if (item.isFormField()) {
			String name = item.getFieldName();
			String value = item.getString(request.getCharacterEncoding());
			serviceRequest.setAttribute(name, value);
		} else {
			processFileField(item, requestContext);
		}
	}
}
 
Example #22
Source File: StyleSheetJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test of doCreateStyleSheet method, of class fr.paris.lutece.portal.web.stylesheet.StyleSheetJspBean.
 * 
 * @throws IOException
 * @throws AccessDeniedException
 */
public void testDoCreateStyleSheet( ) throws IOException, AccessDeniedException
{
    MockHttpServletRequest request = new MockHttpServletRequest( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    final String randomName = getRandomName( );
    parameters.put( Parameters.STYLESHEET_NAME, new String [ ] {
        randomName
    } );
    parameters.put( Parameters.STYLES, new String [ ] {
        Integer.toString( style.getId( ) )
    } );
    parameters.put( Parameters.MODE_STYLESHEET, new String [ ] {
        "0"
    } );
    parameters.put( SecurityTokenService.PARAMETER_TOKEN, new String [ ] {
        SecurityTokenService.getInstance( ).getToken( request, "admin/stylesheet/create_stylesheet.html" )
    } );
    Map<String, List<FileItem>> multipartFiles = new HashMap<>( );
    List<FileItem> items = new ArrayList<>( );
    FileItem source = new DiskFileItemFactory( ).createItem( Parameters.STYLESHEET_SOURCE, "application/xml", true, randomName );
    source.getOutputStream( ).write( "<a/>".getBytes( ) );
    items.add( source );
    multipartFiles.put( Parameters.STYLESHEET_SOURCE, items );
    MultipartHttpServletRequest multipart = new MultipartHttpServletRequest( request, multipartFiles, parameters );
    try
    {
        instance.doCreateStyleSheet( multipart );
        assertTrue( StyleSheetHome.getStyleSheetList( 0 ).stream( ).anyMatch( stylesheet -> stylesheet.getDescription( ).equals( randomName ) ) );
    }
    finally
    {
        StyleSheetHome.getStyleSheetList( 0 ).stream( ).filter( stylesheet -> stylesheet.getDescription( ).equals( randomName ) )
                .forEach( stylesheet -> StyleSheetHome.remove( stylesheet.getId( ) ) );
    }
}
 
Example #23
Source File: ImportPlaylistController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 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, format, item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
Example #24
Source File: Uploader.java    From jeewx with Apache License 2.0 5 votes vote down vote up
private void parseParams() {

		DiskFileItemFactory dff = new DiskFileItemFactory();
		try {
			ServletFileUpload sfu = new ServletFileUpload(dff);
			sfu.setSizeMax(this.maxSize);
			sfu.setHeaderEncoding(Uploader.ENCODEING);

			FileItemIterator fii = sfu.getItemIterator(this.request);

			while (fii.hasNext()) {
				FileItemStream item = fii.next();
				// 普通参数存储
				if (item.isFormField()) {

					this.params.put(item.getFieldName(),
							this.getParameterValue(item.openStream()));

				} else {

					// 只保留一个
					if (this.inputStream == null) {
						this.inputStream = item.openStream();
						this.originalName = item.getName();
						return;
					}

				}

			}

		} catch (Exception e) {
			this.state = this.errorInfo.get("UNKNOWN");
		}

	}
 
Example #25
Source File: Oper.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param request
 * @param response 
 */
private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
if (PDLog.isDebug())
    PDLog.Debug("InsFile");
FileItem ItemFile=null;    
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileData=item.getInputStream();
        ItemFile=item;
        }
    }
DriverGeneric PDSession=getSessOPD(Req);
String Id=(String) ListFields.get("Id");
String Ver=(String) ListFields.get("Ver");
PDSession.InsertFile(Id, Ver, FileData);
if (FileData!=null)
    FileData.close();
if (ItemFile!=null)
    ItemFile.delete();
items.clear(); // to help and speed gc
PrintWriter out = response.getWriter(); 
Answer(Req, out, true, null, null);
out.close();
}
 
Example #26
Source File: FileHandle.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public static Iterator<FileItem>  createFactory(HttpServletRequest request, HttpServletResponse response) throws Exception{
	try{
	// 创建一个磁盘文件的工厂,然后将它 传递到servletFileUplaod的实例中
	DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
	ServletFileUpload servletFileUpload = new ServletFileUpload(
			diskFileItemFactory);
	// 根据request对象获取所有的文件集合,这里包括input标签输入的值也属于FileInput
	List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
	return  fileItemList.iterator();
} catch (Exception e) {
	e.printStackTrace();
	throw new Exception("磁盘文件的工厂创建失败!");
}
}
 
Example #27
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 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));
    // 设置上传限制
    int uploadLimit = FrameworkConstant.UPLOAD_LIMIT;
    if (uploadLimit != 0) {
        fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024); // 单位为 M
    }
}
 
Example #28
Source File: PortletUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, 
 * parses the request, processes the uploaded items and then returns the first file as an
 * <code>UploadedFile</code> object.
 * @param portletRequest The input portlet request
 * @return	The first uploaded file object.
 */
public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest){
	UploadedFile uploadedFile = null;
	try{
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//		 Create a new file upload handler
		PortletFileUpload upload = new PortletFileUpload(factory);
	
		//		 Parse the request
		List /* FileItem */ items = upload.parseRequest((ActionRequest)portletRequest);
	
	
		//		 Process the uploaded items
		Iterator iter = items.iterator();
		boolean endLoop = false;
		while (iter.hasNext() && !endLoop) {
			FileItem item = (FileItem) iter.next();

			if (item.isFormField()) {
				//serviceRequest.setAttribute(item.getFieldName(), item.getString());
			} else {
				uploadedFile = new UploadedFile();
				uploadedFile.setFileContent(item.get());
				uploadedFile.setFieldNameInForm(item.getFieldName());
				uploadedFile.setSizeInBytes(item.getSize());
				uploadedFile.setFileName(item.getName());
				
				endLoop = true;
			}
		}
	}catch(Exception e){
		logger.error("Cannot parse multipart request", e);
	}
	return uploadedFile;
	
}
 
Example #29
Source File: Proxy.java    From odo with Apache License 2.0 5 votes vote down vote up
private DiskFileItemFactory createDiskFactory() {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    return diskFileItemFactory;
}
 
Example #30
Source File: Oper.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param request
 * @param response 
 */
private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
if (PDLog.isDebug())
    PDLog.Debug("InsFile");
FileItem ItemFile=null;    
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileData=item.getInputStream();
        ItemFile=item;
        }
    }
DriverGeneric PDSession=SParent.getSessOPD(Req);
String Id=(String) ListFields.get("Id");
String Ver=(String) ListFields.get("Ver");
PDSession.InsertFile(Id, Ver, FileData);
if (FileData!=null)
    FileData.close();
if (ItemFile!=null)
    ItemFile.delete();
items.clear(); // to help and speed gc
PrintWriter out = response.getWriter(); 
Answer(Req, out, true, null, null);
out.close();
}