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

The following examples show how to use org.apache.commons.fileupload.disk.DiskFileItemFactory. These examples are extracted from open source projects. 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 Project: uccn   Source File: TestFastDfs.java    License: 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 2
/**
 *
 * @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 3
Source Project: openrasp-testcases   Source File: Multipart_mysql.java    License: 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 4
Source Project: urule   Source File: FrameServletHandler.java    License: 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 5
Source Project: urule   Source File: PackageServletHandler.java    License: 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 6
/**
 * 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 7
/**
 * 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 8
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 9
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 10
Source Project: odo   Source File: HttpUtilities.java    License: 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
/**
 * 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 12
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 13
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 14
Source Project: AndroidWebServ   Source File: HttpUpHandler.java    License: 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 15
Source Project: journaldev   Source File: ActionRequestReader.java    License: 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 16
Source Project: jeewx-boot   Source File: MyJwWebJwidController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * url转变为 MultipartFile对象
 * @param url
 * @param fileName
 * @return
 * @throws Exception
 */
private static MultipartFile createFileItem(String url, String fileName) throws Exception{
 FileItem item = null;
 try {
	 HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
	 conn.setReadTimeout(30000);
	 conn.setConnectTimeout(30000);
	 //设置应用程序要从网络连接读取数据
	 conn.setDoInput(true);
	 conn.setRequestMethod("GET");
	 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
		 InputStream is = conn.getInputStream();

		 FileItemFactory factory = new DiskFileItemFactory(16, null);
		 String textFieldName = "uploadfile";
		 item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
		 OutputStream os = item.getOutputStream();

		 int bytesRead = 0;
		 byte[] buffer = new byte[8192];
		 while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
			 os.write(buffer, 0, bytesRead);
		 }
		 os.close();
		 is.close();
	 }
 } catch (IOException e) {
	 throw new RuntimeException("文件下载失败", e);
 }

 return new CommonsMultipartFile(item);
}
 
Example 17
@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 Project: kk-anti-reptile   Source File: ValidateFormService.java    License: Apache License 2.0 5 votes vote down vote up
public String validate(HttpServletRequest request) throws UnsupportedEncodingException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    Map<String, String> params = new HashMap<String, String>();
    for(Object object : items){
        FileItem fileItem = (FileItem) object;
        if (fileItem.isFormField()) {
            params.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
        }
    }
    String verifyId = params.get("verifyId");
    String result =  params.get("result");
    String realRequestUri = params.get("realRequestUri");
    String actualResult = verifyImageUtil.getVerifyCodeFromRedis(verifyId);
    if (actualResult != null && request != null && actualResult.equals(result.toLowerCase())) {
        actuator.reset(request, realRequestUri);
        return "{\"result\":true}";
    }
    return "{\"result\":false}";
}
 
Example 19
Source Project: java_study   Source File: HelloController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/upload")
public String uploadFile(HttpServletRequest request) throws Exception {
    System.out.println("文件上传..");
    // 获取到需要上传文件的路径
    String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
    // 获取file路径,向路径上传文件
    File file = new File(realPath);
    // 判断路径是否存在
    if (!file.exists()) {
        file.mkdirs();
    }
    // 创建磁盘文件工厂方法
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    // 解析request对象
    List<FileItem> list = fileUpload.parseRequest(request);
    // 遍历
    for (FileItem item : list) {
        // 判断是普通字段还是文件上传
        if (item.isFormField()) {
        } else {
            // 获取到上传文件的名称
            String fileName = item.getName();
            String uuid = UUID.randomUUID().toString().replace("-","");
            fileName = uuid + "_" + fileName;
            // 上传文件
            item.write(new File(file, fileName));
            // 删除临时文件
            item.delete();
        }
    }
    return "success";
}
 
Example 20
private static List<FileItem> parseMultipartRequest(Request request)
        throws FileUploadException {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletContext servletContext = request.raw().getServletContext();
    File repository = (File) servletContext
            .getAttribute("javax.servlet.context.tempdir");
    fileItemFactory.setRepository(repository);
    return new ServletFileUpload(fileItemFactory).parseRequest(request.raw());
}
 
Example 21
Source Project: s2g-zuul   Source File: FilterScriptManagerServlet.java    License: MIT License 5 votes vote down vote up
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        org.apache.commons.fileupload.FileItemIterator it = null;
        try {
            it = upload.getItemIterator(request);

            while (it.hasNext()) {
                FileItemStream stream = it.next();
                InputStream input = stream.openStream();

                // NOTE: we are going to pull the entire stream into memory
                // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
                byte[] uploadedBytes = getBytesFromInputStream(input);
                input.close();

                if (uploadedBytes.length == 0) {
                    setUsageError(400, "ERROR: Body contained no data.", response);
                    return null;
                }

                return new String(uploadedBytes);
            }
        } catch (FileUploadException e) {
            throw new IOException(e.getMessage());
        }
        return null;
    }
 
Example 22
/**
 * Uploads a document's related resource.
 * 
 * The resource will be stored in the folder where the document's files
 * reside using the following pattern: <b>fileVersion</b>-<b>suffix</b>
 * 
 * If no version is specified, the current one is used instead
 * 
 * @param request the current request
 * @param docId Id of the document
 * @param suffix Suffix of the document
 * @param fileVersion id of the file version; if null the latest version
 *        will returned
 * @param docVersion id of the doc version; if null the latest version will
 *        returned
 * 
 * @throws Exception a generic error
 */
@SuppressWarnings("unchecked")
public static void uploadDocumentResource(HttpServletRequest request, String docId, String suffix,
		String fileVersion, String docVersion) throws Exception {
	DocumentDAO docDao = (DocumentDAO) Context.get().getBean(DocumentDAO.class);
	Document doc = docDao.findById(Long.parseLong(docId));

	String ver = docVersion;
	if (StringUtils.isEmpty(ver))
		ver = fileVersion;
	if (StringUtils.isEmpty(ver))
		ver = doc.getFileVersion();

	Storer storer = (Storer) Context.get().getBean(Storer.class);

	DiskFileItemFactory factory = new DiskFileItemFactory();
	// Configure the factory here, if desired.
	ServletFileUpload upload = new ServletFileUpload(factory);
	// Configure the uploader here, if desired.
	List<FileItem> fileItems = upload.parseRequest(request);
	for (FileItem item : fileItems) {
		if (!item.isFormField()) {
			File savedFile = File.createTempFile("", "");
			item.write(savedFile);

			InputStream is = null;
			try {
				is = item.getInputStream();
				storer.store(item.getInputStream(), Long.parseLong(docId),
						storer.getResourceName(doc, ver, suffix));
			} finally {
				if (is != null)
					is.close();
				FileUtils.forceDelete(savedFile);
			}
		}
	}
}
 
Example 23
/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * 
 * @param nSizeThreshold
 *            the size threshold
 * @param nRequestSizeMax
 *            the request size max
 * @param bActivateNormalizeFileName
 *            true if the file name must be normalized, false otherwise
 * @param request
 *            the HTTP request
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException
 *             exception if the file size is too big
 * @throws FileUploadException
 *             exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert( int nSizeThreshold, long nRequestSizeMax, boolean bActivateNormalizeFileName,
        HttpServletRequest request ) throws FileUploadException
{
    if ( !isMultipart( request ) )
    {
        return null;
    }

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

    // Set factory constraints
    factory.setSizeThreshold( nSizeThreshold );

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

    // Set overall request size constraint
    upload.setSizeMax( nRequestSizeMax );

    // get encoding to be used
    String strEncoding = Optional.ofNullable( request.getCharacterEncoding( ) ).orElse( EncodingService.getEncoding( ) );

    Map<String, List<FileItem>> mapFiles = new HashMap<>( );
    Map<String, String [ ]> mapParameters = new HashMap<>( );

    List<FileItem> listItems = upload.parseRequest( request );

    // Process the uploaded items
    for ( FileItem item : listItems )
    {
        processItem( item, strEncoding, bActivateNormalizeFileName, mapFiles, mapParameters );
    }

    return new MultipartHttpServletRequest( request, mapFiles, mapParameters );
}
 
Example 24
@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 25
@PostMapping
protected String handlePost(RedirectAttributes redirectAttributes,
                            HttpServletRequest request
) {
    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 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 26
Source Project: Android-Basics-Codes   Source File: UploadServlet.java    License: Artistic License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	// �ж��ϴ����Ƿ�����ļ�
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		// ��ȡ·��
		String realpath = request.getSession().getServletContext()
				.getRealPath("/files");
		System.out.println(realpath);

		File dir = new File(realpath);
		if (!dir.exists())
			dir.mkdirs();
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			// ����������� ��ʵ���� form����ÿ��input�ڵ�
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// ����DZ� ����ÿ���� ��ӡ������̨
					String name1 = item.getFieldName();// �õ��������������
					String value = item.getString("UTF-8");// �õ�����ֵ
					System.out.println(name1 + "=" + value);
				} else {
					// ���ļ�д����ǰservlet����Ӧ��·��
					item.write(new File(dir, System.currentTimeMillis()
							+ item.getName().substring(
									item.getName().lastIndexOf("."))));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 27
Source Project: tutorials   Source File: UploadServlet.java    License: MIT License 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            try {
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
        }
    }
 
Example 28
Source Project: fess   Source File: FessMultipartRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected ServletFileUpload createServletFileUpload(final HttpServletRequest request) {
    final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
    final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax());
    return upload;
}
 
Example 29
/**
 * 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 30
Source Project: fixflow   Source File: FileHandle.java    License: 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("磁盘文件的工厂创建失败!");
}
}