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

The following examples show how to use org.apache.commons.fileupload.FileItem. 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
@Test
public void multipleUpload() throws Exception {
	when(event.getMethod()).thenReturn(uploadMethodController);

	final List<FileItem> elements = new ArrayList<>();
	elements.add(new MockFileItem("myfile0[]", "foo.txt", "foo".getBytes()));
	elements.add(new MockFileItem("myfile0[]", "foo.txt", "bar".getBytes()));

	when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload);
	when(servletFileUpload.parseRequest(request)).thenReturn(elements);

	observer.upload(event, request, config, validator);

	verify(request).setParameter("myfile0[0]", "myfile0[0]");
	verify(request).setParameter("myfile0[1]", "myfile0[1]");

	verify(request).setAttribute(eq("myfile0[0]"), any(UploadedFile.class));
	verify(request).setAttribute(eq("myfile0[1]"), any(UploadedFile.class));
}
 
Example 2
private ProcessCreateResponse processTestRequest(String key, String term,
		String weight, String index, FileItem image) {

	ProcessCreateResponse response = new ProcessCreateResponse(
			this.servletConfig.getServletContext());
	FormItemList testItems = new FormItemList();
	if (key != null) {
		testItems.addField(ProtocolConstants.SUGGESTION_KEY, key);
	}
	if (term != null) {
		testItems.addField(ProtocolConstants.SUGGESTION_STRING, term);
	}
	if (weight != null) {
		testItems.addField(ProtocolConstants.SUGGESTION_WEIGHT, weight);
	}
	if (index != null) {
		testItems.addField(ProtocolConstants.INDEX_PARAMETER, index);
	}
	if (image != null) {
		testItems.addFile(ProtocolConstants.IMAGE, image);
	}
	return ProcessCreateRequest.checkRequestParameter(testItems, response,
			this.servletConfig.getServletContext());
}
 
Example 3
@Override
public void recordUploadedFile(long executionId, TestCaseStepActionExecution tcsae, FileItem uploadedFile) {
    String UploadedfileName = new File(uploadedFile.getName()).getName();

    try {
        // UPLOADED File.
        Recorder recorder = this.initFilenames(executionId, tcsae.getTest(), tcsae.getTestCase(), String.valueOf(tcsae.getStep()), String.valueOf(tcsae.getIndex()), String.valueOf(tcsae.getSequence()), null, null, 0, "image", "jpg", false);
        File storeFile = new File(recorder.getFullFilename());
        // saves the file on disk
        uploadedFile.write(storeFile);
        LOG.info("File saved : " + recorder.getFullFilename());

        // Index file created to database.
        testCaseExecutionFileService.save(executionId, recorder.getLevel(), "Image", recorder.getRelativeFilenameURL(), "JPG", "");

    } catch (Exception ex) {
        LOG.error("File: " + UploadedfileName + " failed to be uploaded/saved: " + ex.toString(), ex);
    }

}
 
Example 4
@EntityCustomAction(action = "uploadImage", viewKey = EntityView.VIEW_NEW)
public String uploadImage(EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String siteId = (String) params.get("siteId");
    FileItem fileItem = (FileItem) params.get("imageFile");
    String contentType = fileItem.getContentType();
    if (!contentTypes.contains(contentType)) {
        throw new EntityException("Invalid image type supplied.", "", HttpServletResponse.SC_BAD_REQUEST);
    }
    String url = sakaiProxy.storeFile(fileItem, siteId);

    if (url == null) {
        throw new EntityException("Failed to save file", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return url;
}
 
Example 5
@EntityCustomAction(action = "uploadImage", viewKey = EntityView.VIEW_NEW)
public String uploadImage(EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String siteId = (String) params.get("siteId");
    FileItem fileItem = (FileItem) params.get("imageFile");
    String contentType = fileItem.getContentType();
    if (!contentTypes.contains(contentType)) {
        throw new EntityException("Invalid image type supplied.", "", HttpServletResponse.SC_BAD_REQUEST);
    }
    String url = sakaiProxy.storeFile(fileItem, siteId);

    if (url == null) {
        throw new EntityException("Failed to save file", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return url;
}
 
Example 6
@Test
public void withFieldsOnly() throws Exception {
	when(event.getMethod()).thenReturn(uploadMethodController);

	final List<FileItem> elements = new ArrayList<>();
	elements.add(new MockFileItem("foo", "blah"));
	elements.add(new MockFileItem("bar", "blah blah"));

	when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload);
	when(servletFileUpload.parseRequest(request)).thenReturn(elements);
	when(request.getCharacterEncoding()).thenReturn("UTF-8");

	observer.upload(event, request, config, validator);

	verify(request).setParameter("foo", "blah");
	verify(request).setParameter("bar", "blah blah");
}
 
Example 7
/**
 * 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 8
@Test
public void readsEntityStreamAsIteratorOfFileItems() throws Exception {
    Class type = Iterator.class;
    ParameterizedType genericType = newParameterizedType(Iterator.class, FileItem.class);
    Annotation[] annotations = new Annotation[0];
    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    InputStream in = mock(InputStream.class);

    mockHttpServletRequest();

    Iterator<FileItem> fileItems = formDataEntityProvider.readFrom(type, genericType, annotations, null, headers, in);
    List<FileItem> fileItemList = Lists.newArrayList(fileItems);
    assertEquals(1, fileItemList.size());
    assertEquals("text", fileItemList.get(0).getFieldName());
    assertEquals("test.txt", fileItemList.get(0).getName());
    assertEquals("text/plain", fileItemList.get(0).getContentType());
    assertEquals("hello", fileItemList.get(0).getString());
}
 
Example 9
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 10
@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 11
Source Project: unitime   Source File: ScriptExecution.java    License: Apache License 2.0 5 votes vote down vote up
public ScriptExecution(ExecuteScriptRpcRequest request, SessionContext context) {
	super(context.getUser());
	iRequest = request;
	
	Script script = ScriptDAO.getInstance().get(request.getScriptId());
	if (script.getPermission() != null)
		context.checkPermission(Right.valueOf(script.getPermission().replace(" ", "")));
	
	for (ScriptParameter parameter: script.getParameters())
		if ("file".equals(parameter.getType()))
			iFile = (FileItem)context.getAttribute(SessionAttribute.LastUploadedFile);
}
 
Example 12
/**
 * Test of doCreatePageTemplate method, of fr.paris.lutece.portal.web.style.PageTemplatesJspBean.
 * 
 * @throws AccessDeniedException
 * @throws IOException
 */
public void testDoCreatePageTemplate( ) throws AccessDeniedException, IOException
{
    final String desc = getRandomName( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.PAGE_TEMPLATE_DESCRIPTION, new String [ ] {
        desc
    } );
    parameters.put( SecurityTokenService.PARAMETER_TOKEN, new String [ ] {
        SecurityTokenService.getInstance( ).getToken( request, "admin/style/create_page_template.html" )
    } );
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( );
    Map<String, List<FileItem>> files = new HashMap<>( );
    List<FileItem> pageTemplateFiles = new ArrayList<>( );
    FileItem pageTemplateFile = fileItemFactory.createItem( "page_template_file", "text/html", false, "junit.html" );
    pageTemplateFile.getOutputStream( ).write( new byte [ 1] );
    pageTemplateFiles.add( pageTemplateFile );
    files.put( "page_template_file", pageTemplateFiles );
    List<FileItem> pageTemplatePictures = new ArrayList<>( );
    FileItem pageTemplatePicture = fileItemFactory.createItem( "page_template_picture", "image/jpg", false, "junit.jpg" );
    pageTemplatePicture.getOutputStream( ).write( new byte [ 1] );
    pageTemplatePictures.add( pageTemplatePicture );
    files.put( "page_template_picture", pageTemplatePictures );
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest( request, files, parameters );
    try
    {
        instance.doCreatePageTemplate( multipartRequest );
        assertTrue( PageTemplateHome.getPageTemplatesList( ).stream( ).anyMatch( t -> t.getDescription( ).equals( desc ) ) );
    }
    finally
    {
        PageTemplateHome.getPageTemplatesList( ).stream( ).filter( t -> t.getDescription( ).equals( desc ) )
                .forEach( t -> PageTemplateHome.remove( t.getId( ) ) );
    }
}
 
Example 13
Source Project: sakai   Source File: WebServlet.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Handle file upload requests.
 * 
 * @param req
 * @param res
 */
protected void postUpload(HttpServletRequest req, HttpServletResponse res)
{
	String path = req.getPathInfo();
	log.debug("path {}", path);
	if (path == null) path = "";
	// assume caller has verified that it is a request for content and that it's multipart
	// loop over attributes in request, picking out the ones
	// that are file uploads and doing them
	for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();)
	{
		String iname = (String) e.nextElement();
		log.debug("Item {}", iname);
		Object o = req.getAttribute(iname);
		// NOTE: Fileitem is from
		// org.apache.commons.fileupload.FileItem, not
		// sakai's parameterparser version
		if (o != null && o instanceof FileItem)
		{
			FileItem fi = (FileItem) o;
			try (InputStream inputStream = fi.getInputStream())
			{
				if (!writeFile(fi.getName(), fi.getContentType(), inputStream, path, req, res, true)) return;
			} catch (IOException ioe) {
				log.warn("Problem getting InputStream", ioe);
			}
		}
	}
}
 
Example 14
@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 15
private JSONObject uploadFile() throws Exception{		
	FileItem uploaded = (FileItem) getAttribute(UPLOADED_FILE);
	
	if (uploaded == null) {
		throw new SpagoBIServiceException(getActionName(), "No file was uploaded");
	}
	
	UserProfile userProfile = (UserProfile) this.getUserProfile();
	logger.info("User [id : " + userProfile.getUserId() + ", name : " + userProfile.getUserName() + "] " +
			"is uploading file [" + uploaded.getName() + "] with size [" + uploaded.getSize() + "]");
	
	int maxSize = Integer.parseInt( SingletonConfig.getInstance().getConfigValue("SPAGOBI.DOCUMENTS.MAX_PREVIEW_IMAGE_SIZE") );
	FileUtils.checkUploadedFile(uploaded, maxSize, VALID_FILE_EXTENSIONS);
	
	File targetDirectory = GeneralUtilities.getPreviewFilesStorageDirectoryPath();
	
	// check if number of existing images is the max allowed
	int maxFilesAllowed = Integer.parseInt( SingletonConfig.getInstance().getConfigValue("SPAGOBI.DOCUMENTS.MAX_PREVIEW_IMAGES_NUM") );
	FileUtils.checkIfFilesNumberExceedsInDirectory(targetDirectory, maxFilesAllowed);
	
	logger.debug("Saving file...");
	File saved = FileUtils.saveFileIntoDirectory(uploaded, targetDirectory);
	logger.debug("File saved");
	
	JSONObject toReturn = new JSONObject();
	try {				
		toReturn.put("success", true);
		toReturn.put("file","null");
		toReturn.put("fileName", saved.getName());
	} catch (JSONException jSONException) {
		logger.error(jSONException);
	}

	return toReturn;
	
}
 
Example 16
@Test
public void ensureCopyUploadedFileToOutputStream() throws IOException {
	File outputFile = tmpdir.newFile();
	OutputStream outputStream = new FileOutputStream(outputFile);

	byte[] byteOnlyFileContent = { 0x0, 0x1, 0x2 };
	FileItem mockedFileItem = mock(FileItem.class);
	when(mockedFileItem.getInputStream()).thenReturn(new ByteArrayInputStream(byteOnlyFileContent));

	UploadedFile file = new CommonsUploadedFile(mockedFileItem);
	file.writeTo(outputStream);

	assertThat(outputFile.length(), is(new Long(byteOnlyFileContent.length)));
	assertThat(Files.readAllBytes(outputFile.toPath()), is(byteOnlyFileContent));
}
 
Example 17
public void testDoImportUsersFromFile( ) throws AccessDeniedException, UserNotSignedException, IOException
{
    AdminUserJspBean bean = new AdminUserJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    request.addParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "jsp/admin/user/ImportUser.jsp" ) );
    AdminUser user = getUserToModify( );
    AdminAuthenticationService.getInstance( ).registerUser( request, user );
    bean.init( request, "CORE_USERS_MANAGEMENT" );
    Map<String, List<FileItem>> multipartFiles = new HashMap<>( );
    List<FileItem> fileItems = new ArrayList<>( );
    FileItem file = new DiskFileItem( "import_file", "application/csv", true, "junit.csv", 1024, new File( System.getProperty( "java.io.tmpdir" ) ) );
    OutputStreamWriter writer = new OutputStreamWriter( file.getOutputStream( ), Charset.forName( "UTF-8" ) );
    writer.write( "test;test;test;[email protected];" + AdminUser.ACTIVE_CODE + ";" + Locale.FRANCE + ";0;false;false;;;" );
    writer.close( );
    fileItems.add( file );
    multipartFiles.put( "import_file", fileItems );
    Map<String, String [ ]> parameters = request.getParameterMap( );
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest( request, multipartFiles, parameters );
    bean.getImportUsersFromFile( request ); // initialize _importAdminUserService
    AdminUser importedUser = null;
    try
    {
        bean.doImportUsersFromFile( multipartRequest );
        importedUser = AdminUserHome.findUserByLogin( "test" );
        assertNotNull( importedUser );
        assertEquals( "test", importedUser.getAccessCode( ) );
        assertEquals( "test", importedUser.getFirstName( ) );
        assertEquals( "test", importedUser.getLastName( ) );
        assertEquals( "[email protected]", importedUser.getEmail( ) );
        assertEquals( AdminUser.ACTIVE_CODE, importedUser.getStatus( ) );
    }
    finally
    {
        if ( importedUser != null )
        {
            disposeOfUser( importedUser );
        }
        disposeOfUser( user );
    }
}
 
Example 18
Source Project: mirror   Source File: WebServer.java    License: Apache License 2.0 5 votes vote down vote up
private String saveFileItemToDisk(FileItem fileItem) {
    Timber.d("Received file %s", fileItem.getName());
    try {
        File file = getFile(fileItem);
        Timber.d("writing file %s", file.getAbsolutePath());
        fileItem.write(getFile(fileItem));
        return file.getAbsolutePath();
    } catch (Exception e) {
        Timber.e(e, e.getMessage());
        return "";
    }
}
 
Example 19
private void checkFile(FileItem uploaded, File saveTo) {

		int used = getDatasetsNumberUsingFile(uploaded);
		if (used > 0) {
			throw new SpagoBIServiceException(getActionName(), "{NonBlockingError: true, error:\"USED\", used:\"" + used + "\"}");
		}
		boolean alreadyExist = checkFileIfExist(saveTo);
		if (alreadyExist) {
			throw new SpagoBIServiceException(getActionName(), "{NonBlockingError: true, error:\"EXISTS\"}");
		}

	}
 
Example 20
@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 21
private void checkUploadedFile(FileItem uploaded) {
	logger.debug("IN");
	try {
		// check if the uploaded file exceeds the maximum dimension
		int maxSize = GeneralUtilities.getTemplateMaxSize();
		if (uploaded.getSize() > maxSize) {
			throw new SpagoBIEngineServiceException(getActionName(), "The uploaded file exceeds the maximum size, that is " + maxSize);
		}
	} finally {
		logger.debug("OUT");
	}
}
 
Example 22
public void testDoCreatePageTemplateNoToken( ) throws AccessDeniedException, IOException
{
    final String desc = getRandomName( );
    Map<String, String [ ]> parameters = new HashMap<>( );
    parameters.put( Parameters.PAGE_TEMPLATE_DESCRIPTION, new String [ ] {
        desc
    } );
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( );
    Map<String, List<FileItem>> files = new HashMap<>( );
    List<FileItem> pageTemplateFiles = new ArrayList<>( );
    FileItem pageTemplateFile = fileItemFactory.createItem( "page_template_file", "text/html", false, "junit.html" );
    pageTemplateFile.getOutputStream( ).write( new byte [ 1] );
    pageTemplateFiles.add( pageTemplateFile );
    files.put( "page_template_file", pageTemplateFiles );
    List<FileItem> pageTemplatePictures = new ArrayList<>( );
    FileItem pageTemplatePicture = fileItemFactory.createItem( "page_template_picture", "image/jpg", false, "junit.jpg" );
    pageTemplatePicture.getOutputStream( ).write( new byte [ 1] );
    pageTemplatePictures.add( pageTemplatePicture );
    files.put( "page_template_picture", pageTemplatePictures );
    MultipartHttpServletRequest multipartRequest = new MultipartHttpServletRequest( request, files, parameters );
    try
    {
        instance.doCreatePageTemplate( multipartRequest );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        assertFalse( PageTemplateHome.getPageTemplatesList( ).stream( ).anyMatch( t -> t.getDescription( ).equals( desc ) ) );
    }
    finally
    {
        PageTemplateHome.getPageTemplatesList( ).stream( ).filter( t -> t.getDescription( ).equals( desc ) )
                .forEach( t -> PageTemplateHome.remove( t.getId( ) ) );
    }
}
 
Example 23
Source Project: everrest   Source File: MultipartTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInputMultipartFormApache() throws Exception {
    Iterator<FileItem> expected = Iterators.forArray(createFileItem("text/xml", false, "xml-file", "foo.xml", XML_DATA),
                                                     createFileItem("application/json", false, "json-file", "foo.json", JSON_DATA),
                                                     createFileItem(null, true, "field", null, TEXT_DATA));
    processor.addApplication(new Application() {
        @Override
        public Set<Object> getSingletons() {
            return Collections.<Object>singleton(new Resource1(expected));
        }
    });

    doPost("/1");
}
 
Example 24
Source Project: freeacs   Source File: Input.java    License: MIT License 5 votes vote down vote up
/**
 * Gets the file as string.
 *
 * @return the file as string
 */
public String getFileAsString() {
  if (type != InputType.FILE) {
    logger.warn(key + " is not a File");
  }
  if (value instanceof FileItem) {
    return new String(((FileItem) value).get()).trim();
  }
  return null;
}
 
Example 25
private MessageBodyReader createFileItemMessageBodyReader(Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream in,
                                                          FileItem... fileItems) throws Exception {
    MessageBodyReader fileItemReader = mock(MessageBodyReader.class);
    when(fileItemReader.readFrom(eq(Iterator.class), eq(newParameterizedType(Iterator.class, FileItem.class)), aryEq(annotations), eq(mediaType), eq(headers), eq(in)))
            .thenReturn(newArrayList(fileItems).iterator());
    return fileItemReader;
}
 
Example 26
Source Project: freeacs   Source File: Input.java    License: MIT License 5 votes vote down vote up
/**
 * Gets the file.
 *
 * @return the file
 */
public FileItem getFile() {
  if (type != InputType.FILE) {
    logger.warn(key + " is not a File");
  }
  if (value instanceof FileItem) {
    return (FileItem) value;
  }
  return null;
}
 
Example 27
Source Project: freeacs   Source File: ParameterParser.java    License: MIT License 5 votes vote down vote up
/**
 * Gets the file upload array.
 *
 * @param name the name
 * @return the file upload array
 */
public FileItem[] getFileUploadArray(String name) {
  List<FileItem> arr = files.get(name);
  if (arr != null) {
    return arr.toArray(new FileItem[] {});
  }
  return null;
}
 
Example 28
Source Project: freeacs   Source File: FilePage.java    License: MIT License 5 votes vote down vote up
/**
 * Action parse.
 *
 * @param req the req
 * @throws IllegalArgumentException the illegal argument exception
 * @throws SecurityException the security exception
 * @throws IllegalAccessException the illegal access exception
 * @throws InvocationTargetException the invocation target exception
 * @throws NoSuchMethodException the no such method exception
 */
private void actionParse(ParameterParser req) {
  if (!"Clear".equals(formsubmit)) {
    id = inputData.getId().getInteger();
    FileItem file = req.getFileUpload("filename");
    if (file != null) {
      bytes = file.get();
    }
    name = inputData.getName().getStringWithoutTags();
    description = inputData.getDescription().getStringWithoutTagsAndContent();
    String fileTypeStr = inputData.getType().getString();
    if (fileTypeStr != null) {
      fileTypeEnum = FileType.valueOf(fileTypeStr);
    }
    date = inputData.getSoftwaredate().getDateOrDefault(new Date());
    versionNumber = inputData.getVersionNumber().getStringWithoutTags();
    targetName = inputData.getTargetName().getString();
    content = inputData.getContent().getString();
  }

  String item;
  Enumeration<?> names = req.getKeyEnumeration();
  while (names.hasMoreElements() && (item = (String) names.nextElement()) != null) {
    if (item.startsWith("delete::")) {
      deleteList.add(item.substring(8));
    }
  }
}
 
Example 29
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 30
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);
        }
    }