org.apache.commons.fileupload.FileItemFactory Java Examples

The following examples show how to use org.apache.commons.fileupload.FileItemFactory. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: InMemoryMultipartFormDataEntityProvider.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@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 #13
Source File: CommonsMultipartResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #14
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 #15
Source File: AbstractJettyServerTestCase.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #16
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 #17
Source File: AvatarUploadController.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 {

    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 #18
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 #19
Source File: UploadServlet.java    From Android-Basics-Codes with 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 #20
Source File: UploadServlet.java    From Android-Basics-Codes with 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 #21
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 #22
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 #23
Source File: MyJwWebJwidController.java    From jeewx-boot with 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 #24
Source File: ImportPlaylistController.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@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 #25
Source File: AvatarUploadController.java    From airsonic 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 #26
Source File: FilterScriptManagerServlet.java    From s2g-zuul with 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 #27
Source File: ImportPlaylistController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@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 #28
Source File: CommonsMultipartResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #29
Source File: CommonsMultipartResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #30
Source File: FormHttpMessageConverterTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void writeMultipartOrder() throws Exception {
	MyBean myBean = new MyBean();
	myBean.setString("foo");

	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
	parts.add("part1", myBean);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_XML);
	HttpEntity<MyBean> entity = new HttpEntity<MyBean>(myBean, entityHeaders);
	parts.add("part2", entity);

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

	final MediaType contentType = outputMessage.getHeaders().getContentType();
	assertNotNull("No boundary found", contentType.getParameter("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(2, items.size());

	FileItem item = items.get(0);
	assertTrue(item.isFormField());
	assertEquals("part1", item.getFieldName());
	assertEquals("{\"string\":\"foo\"}", item.getString());

	item = items.get(1);
	assertTrue(item.isFormField());
	assertEquals("part2", item.getFieldName());

	// With developer builds we get: <MyBean><string>foo</string></MyBean>
	// But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
	// So... we make a compromise:
	assertThat(item.getString(),
			allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>")));
}