Java Code Examples for org.apache.commons.fileupload.FileItem#getOutputStream()

The following examples show how to use org.apache.commons.fileupload.FileItem#getOutputStream() . 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: 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 2
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 3
Source File: AdminUserJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 4
Source File: AdminUserJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoImportUsersFromFileInvalidToken( ) 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" )
            + "b" );
    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 );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        importedUser = AdminUserHome.findUserByLogin( "test" );
        assertNull( importedUser );
    }
    finally
    {
        if ( importedUser != null )
        {
            disposeOfUser( importedUser );
        }
        disposeOfUser( user );
    }
}
 
Example 5
Source File: AdminUserJspBeanTest.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testDoImportUsersFromFileNoToken( ) throws AccessDeniedException, UserNotSignedException, IOException
{
    AdminUserJspBean bean = new AdminUserJspBean( );
    MockHttpServletRequest request = new MockHttpServletRequest( );
    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 );
        fail( "Should have thrown" );
    }
    catch( AccessDeniedException e )
    {
        importedUser = AdminUserHome.findUserByLogin( "test" );
        assertNull( importedUser );
    }
    finally
    {
        if ( importedUser != null )
        {
            disposeOfUser( importedUser );
        }
        disposeOfUser( user );
    }
}
 
Example 6
Source File: UploadDatasetFileResource.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
private FileItem unzipUploadedFile(FileItem uploaded) {

		logger.debug("Method unzipUploadedFile(): Start");

		FileItem tempFileItem = null;

		try {
			ZipInputStream zippedInputStream = new ZipInputStream(uploaded.getInputStream());
			ZipEntry zipEntry = null;

			if ((zipEntry = zippedInputStream.getNextEntry()) != null) {

				String zipItemName = zipEntry.getName();

				logger.debug("Method unzipUploadedFile(): Zip entry [ " + zipItemName + " ]");

				if (zipEntry.isDirectory()) {
					throw new SpagoBIServiceException(getActionName(), "The uploaded file is a folder. Zip directly the file.");
				}

				DiskFileItemFactory factory = new DiskFileItemFactory();
				tempFileItem = factory.createItem(uploaded.getFieldName(), "application/octet-stream", uploaded.isFormField(), zipItemName);
				OutputStream tempFileItemOutStream = tempFileItem.getOutputStream();

				IOUtils.copy(zippedInputStream, tempFileItemOutStream);

				tempFileItemOutStream.close();
			}

			zippedInputStream.close();

			logger.debug("Method unzipUploadedFile(): End");
			return tempFileItem;

		} catch (Throwable t) {
			logger.error("Error while unzip file. Invalid archive file: " + t);
			throw new SpagoBIServiceException(getActionName(), "Error while unzip file. Invalid archive file", t);

		}
	}
 
Example 7
Source File: UploadDatasetFileResource.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
private FileItem ungzipUploadedFile(FileItem uploaded) {

		logger.debug("Method ungzipUploadedFile(): Start");

		FileItem tempFileItem = null;

		try {
			GZIPInputStream zippedInputStream = new GZIPInputStream(uploaded.getInputStream());

			String gzipItemName = uploaded.getName().lastIndexOf('.') > 0 ? uploaded.getName().substring(0, uploaded.getName().lastIndexOf('.')) : null;

			if (gzipItemName == null || gzipItemName.equals("")) {
				throw new SpagoBIServiceException(getActionName(), "Invalid filename for gzip file");
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			tempFileItem = factory.createItem(uploaded.getFieldName(), "application/octet-stream", uploaded.isFormField(), gzipItemName);
			OutputStream tempFileItemOutStream = tempFileItem.getOutputStream();

			IOUtils.copy(zippedInputStream, tempFileItemOutStream);

			tempFileItemOutStream.close();

			zippedInputStream.close();

			logger.debug("Method ungzipUploadedFile(): End");
			return tempFileItem;

		} catch (Throwable t) {
			logger.error("Error while unzip file. Invalid archive file: " + t);
			throw new SpagoBIServiceException(getActionName(), "Error while unzip file. Invalid archive file", t);

		}
	}
 
Example 8
Source File: UploadDatasetFileAction.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
private FileItem unzipUploadedFile(FileItem uploaded) {

		logger.debug("Method unzipUploadedFile(): Start");

		FileItem tempFileItem = null;

		try {
			ZipInputStream zippedInputStream = new ZipInputStream(uploaded.getInputStream());
			ZipEntry zipEntry = null;

			if ((zipEntry = zippedInputStream.getNextEntry()) != null) {

				String zipItemName = zipEntry.getName();

				logger.debug("Method unzipUploadedFile(): Zip entry [ " + zipItemName + " ]");

				if (zipEntry.isDirectory()) {
					throw new SpagoBIServiceException(getActionName(), "The uploaded file is a folder. Zip directly the file.");
				}

				DiskFileItemFactory factory = new DiskFileItemFactory();
				tempFileItem = factory.createItem(uploaded.getFieldName(), "application/octet-stream", uploaded.isFormField(), zipItemName);
				OutputStream tempFileItemOutStream = tempFileItem.getOutputStream();

				IOUtils.copy(zippedInputStream, tempFileItemOutStream);

				tempFileItemOutStream.close();
			}

			zippedInputStream.close();

			logger.debug("Method unzipUploadedFile(): End");
			return tempFileItem;

		} catch (Throwable t) {
			logger.error("Error while unzip file. Invalid archive file: " + t);
			throw new SpagoBIServiceException(getActionName(), "Error while unzip file. Invalid archive file", t);

		}
	}
 
Example 9
Source File: UploadDatasetFileAction.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
private FileItem ungzipUploadedFile(FileItem uploaded) {

		logger.debug("Method ungzipUploadedFile(): Start");

		FileItem tempFileItem = null;

		try {
			GZIPInputStream zippedInputStream = new GZIPInputStream(uploaded.getInputStream());

			String gzipItemName = uploaded.getName().lastIndexOf('.') > 0 ? uploaded.getName().substring(0, uploaded.getName().lastIndexOf('.')) : null;

			if (gzipItemName == null || gzipItemName.equals("")) {
				throw new SpagoBIServiceException(getActionName(), "Invalid filename for gzip file");
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			tempFileItem = factory.createItem(uploaded.getFieldName(), "application/octet-stream", uploaded.isFormField(), gzipItemName);
			OutputStream tempFileItemOutStream = tempFileItem.getOutputStream();

			IOUtils.copy(zippedInputStream, tempFileItemOutStream);

			tempFileItemOutStream.close();

			zippedInputStream.close();

			logger.debug("Method ungzipUploadedFile(): End");
			return tempFileItem;

		} catch (Throwable t) {
			logger.error("Error while unzip file. Invalid archive file: " + t);
			throw new SpagoBIServiceException(getActionName(), "Error while unzip file. Invalid archive file", t);

		}
	}