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

The following examples show how to use org.apache.commons.fileupload.FileItemFactory. 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
/**
 * 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 3
/**
 * 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 4
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 5
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 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 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
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 10
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 11
@SuppressWarnings("unchecked")
@Override
public Iterator<FileItem> readFrom(Class<Iterator<FileItem>> type,
                                   Type genericType,
                                   Annotation[] annotations,
                                   MediaType mediaType,
                                   MultivaluedMap<String, String> httpHeaders,
                                   InputStream entityStream) throws IOException {
    try {
        ApplicationContext context = ApplicationContext.getCurrent();
        int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
        FileItemFactory factory = new InMemoryItemFactory(bufferSize);
        FileUpload upload = new FileUpload(factory);
        return upload.parseRequest(httpRequest).iterator();
    } catch (FileUploadException e) {
        throw new IOException(String.format("Can't process multipart data item, %s", e));
    }
}
 
Example 12
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 13
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 14
@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 15
@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 16
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example 17
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example 18
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 19
@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 20
@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 21
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 Project: carbon-identity-framework   Source File: SecurityUIUtil.java    License: 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 23
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<FileItem>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example 24
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	assertTrue(ServletFileUpload.isMultipartContent(req));
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	try {
		List<FileItem> items = upload.parseRequest(req);
		assertEquals(4, items.size());
		FileItem item = items.get(0);
		assertTrue(item.isFormField());
		assertEquals("name 1", item.getFieldName());
		assertEquals("value 1", item.getString());

		item = items.get(1);
		assertTrue(item.isFormField());
		assertEquals("name 2", item.getFieldName());
		assertEquals("value 2+1", item.getString());

		item = items.get(2);
		assertTrue(item.isFormField());
		assertEquals("name 2", item.getFieldName());
		assertEquals("value 2+2", item.getString());

		item = items.get(3);
		assertFalse(item.isFormField());
		assertEquals("logo", item.getFieldName());
		assertEquals("logo.jpg", item.getName());
		assertEquals("image/jpeg", item.getContentType());
	}
	catch (FileUploadException ex) {
		throw new ServletException(ex);
	}

}
 
Example 25
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 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));
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
 
Example 26
@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 27
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 28
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 29
Source Project: attic-stratos   Source File: AbstractFileUploadExecutor.java    License: 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 30
@Test
public void writeMultipart() throws Exception {
	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("name 1", "value 1");
	parts.add("name 2", "value 2+1");
	parts.add("name 2", "value 2+2");
	parts.add("name 3", null);

	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	parts.add("logo", logo);

	// SPR-12108
	Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
		@Override
		public String getFilename() {
			return "Hall\u00F6le.jpg";
		}
	};
	parts.add("utf8", utf8);

	Source xml = new StreamSource(new StringReader("<root><child/></root>"));
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
	parts.add("xml", entity);

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	// SPR-17030
	assertThat(contentType.getParameters().keySet(), Matchers.contains("charset", "boundary"));

	// see if Commons FileUpload can read what we wrote
	FileItemFactory fileItemFactory = new DiskFileItemFactory();
	FileUpload fileUpload = new FileUpload(fileItemFactory);
	RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
	List<FileItem> items = fileUpload.parseRequest(requestContext);
	assertEquals(6, items.size());
	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("name 1", item.getFieldName());
	assertEquals("value 1", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+1", item.getString());

	item = items.get(2);
	assertTrue(item.isFormField());
	assertEquals("name 2", item.getFieldName());
	assertEquals("value 2+2", item.getString());

	item = items.get(3);
	assertFalse(item.isFormField());
	assertEquals("logo", item.getFieldName());
	assertEquals("logo.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(4);
	assertFalse(item.isFormField());
	assertEquals("utf8", item.getFieldName());
	assertEquals("Hall\u00F6le.jpg", item.getName());
	assertEquals("image/jpeg", item.getContentType());
	assertEquals(logo.getFile().length(), item.getSize());

	item = items.get(5);
	assertEquals("xml", item.getFieldName());
	assertEquals("text/xml", item.getContentType());
	verify(outputMessage.getBody(), never()).close();
}