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

The following examples show how to use org.apache.commons.fileupload.FileItem#getContentType() . 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: CommonsEntityProvider.java    From sakai with Educational Community License v2.0 7 votes vote down vote up
@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 2
Source File: CommonsEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@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 3
Source File: AdminPageJspBean.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Update the page's picture
 * 
 * @param mRequest
 *            the request
 * @param page
 *            the page
 * @return an error URL, or <code>null</code>
 */
private String updatePicture( MultipartHttpServletRequest mRequest, Page page )
{
    String strUpdatePicture = mRequest.getParameter( PARAMETER_PAGE_TEMPLATE_UPDATE_IMAGE );
    if ( strUpdatePicture == null )
    {
        return null;
    }

    FileItem item = mRequest.getFile( PARAMETER_IMAGE_CONTENT );
    String strPictureName = FileUploadService.getFileNameOnly( item );

    if ( strPictureName.equals( "" ) )
    {
        return AdminMessageService.getMessageUrl( mRequest, Messages.MANDATORY_FILE, AdminMessage.TYPE_STOP );
    }
    byte [ ] bytes = item.get( );
    String strMimeType = item.getContentType( );
    page.setImageContent( bytes );
    page.setMimeType( strMimeType );
    return null;
}
 
Example 4
Source File: JobUploadService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException {
	String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    
    if(fieldName.equalsIgnoreCase("deploymentDescriptor")) return null;
    
    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    File jobsDir = new File(runtimeRepository.getRootDir(), jobDeploymentDescriptor.getLanguage().toLowerCase());
	File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject());
	File tmpDir = new File(projectDir, "tmp");
	if(!tmpDir.exists()) tmpDir.mkdirs();	   
     File uploadedFile = new File(tmpDir, fileName);
    
    try {
		item.write(uploadedFile);
	} catch (Exception e) {
		e.printStackTrace();
	}	
	
	String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2);
	List dirNameList = new ArrayList();
	for(int i = 0; i < dirNames.length; i++) {
		if(!dirNames[i].equalsIgnoreCase("lib")) dirNameList.add(dirNames[i]);
	}
	String[] jobNames = (String[])dirNameList.toArray(new String[0]);
	
    runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile));
    uploadedFile.delete();	
    tmpDir.delete();
    
    return jobNames;
}
 
Example 5
Source File: JobUploadService.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private void publishOnSpagoBI(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException {
	String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    
    if(fieldName.equalsIgnoreCase("deploymentDescriptor")) return;
    
    
    
    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    
    String projectName = jobDeploymentDescriptor.getProject();
    String projectLanguage = jobDeploymentDescriptor.getLanguage().toLowerCase();
    String jobName = "JOB_NAME";
    String contextName = "Default";
    String template = "";
    template += "<etl>\n";
    template += "\t<job project=\"" + projectName + "\" ";
    template += "jobName=\"" + projectName + "\" ";
    template += "context=\"" + projectName + "\" ";
    template += "language=\"" + contextName + "\" />\n";
    template += "</etl>";
    
    BASE64Encoder encoder = new BASE64Encoder();
    String templateBase64Coded = encoder.encode(template.getBytes());		
    
    TalendEngineConfig config = TalendEngineConfig.getInstance();
    
    String user = "biadmin";
	String password = "biadmin";
	String label = "ETL_JOB";
	String name = "EtlJob";
	String description = "Etl Job";
	boolean encrypt = false;
	boolean visible = true;
	String functionalitiyCode = config.getSpagobiTargetFunctionalityLabel();	
	String type = "ETL";
	String state = "DEV";
    
    try {

    	//PublishAccessUtils.publish(spagobiurl, user, password, label, name, description, encrypt, visible, type, state, functionalitiyCode, templateBase64Coded);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
}
 
Example 6
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 4 votes vote down vote up
/**
 * 创建 multipart 请求参数列表
 */
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
    // 定义参数列表
    List<Object> paramList = new ArrayList<Object>();
    // 创建两个对象,分别对应 普通字段 与 文件字段
    Map<String, Object> fieldMap = new HashMap<String, Object>();
    List<Multipart> multipartList = new ArrayList<Multipart>();
    // 获取并遍历表单项
    List<FileItem> fileItemList;
    try {
        fileItemList = fileUpload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // 异常转换(抛出自定义异常)
        throw new UploadException(e);
    }
    for (FileItem fileItem : fileItemList) {
        // 分两种情况处理表单项
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // 处理普通字段
            String fieldValue = fileItem.getString(FrameworkConstant.UTF_8);
            fieldMap.put(fieldName, fieldValue);
        } else {
            // 处理文件字段
            String fileName = FileUtil.getRealFileName(fileItem.getName());
            if (StringUtil.isNotEmpty(fileName)) {
                long fileSize = fileItem.getSize();
                String contentType = fileItem.getContentType();
                InputStream inputSteam = fileItem.getInputStream();
                // 创建 Multipart 对象,并将其添加到 multipartList 中
                Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam);
                multipartList.add(multipart);
            }
        }
    }
    // 初始化参数列表
    paramList.add(new Params(fieldMap));
    paramList.add(new Multiparts(multipartList));
    // 返回参数列表
    return paramList;
}
 
Example 7
Source File: podHomeBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
	 * Creates a BufferedInputStream to get ready to upload file selected. Used
	 * by Add Podcast and Revise Podcast pages.
	 * 
	 * @param event
	 *            ValueChangeEvent object generated by selecting a file to
	 *            upload.
	 *            
	 * @throws AbortProcessingException
	 * 			Internal processing error attempting to set up BufferedInputStream
	 */
	public void processFileUpload(ValueChangeEvent event)
			throws AbortProcessingException {
		UIComponent component = event.getComponent();

		Object newValue = event.getNewValue();
		Object oldValue = event.getOldValue();
		PhaseId phaseId = event.getPhaseId();
		Object source = event.getSource();
//		log.info("processFileUpload() event: " + event
//				+ " component: " + component + " newValue: " + newValue
//				+ " oldValue: " + oldValue + " phaseId: " + phaseId
//				+ " source: " + source);

		if (newValue instanceof String)
			return;
		if (newValue == null)
			return;

		FileItem item = (FileItem) event.getNewValue();
		String fieldName = item.getFieldName();
		filename = FilenameUtils.getName(item.getName());
		fileSize = item.getSize();
		fileContentType = item.getContentType();
//		log.info("processFileUpload(): item: " + item
//				+ " fieldname: " + fieldName + " filename: " + filename
//				+ " length: " + fileSize);

		// Read the file as a stream (may be more memory-efficient)
		try {
			fileAsStream = new BufferedInputStream(item.getInputStream());
			
		} 
		catch (IOException e) {
			log.warn("IOException while attempting to set BufferedInputStream to upload "
							+ filename + " from site " + podcastService.getSiteId() + ". "
									 + e.getMessage(), e);
			setErrorMessage(INTERNAL_ERROR_ALERT);

		}

	}
 
Example 8
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 4 votes vote down vote up
/**
 * 创建 multipart 请求参数列表
 */
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
    // 定义参数列表
    List<Object> paramList = new ArrayList<Object>();
    // 创建两个对象,分别对应 普通字段 与 文件字段
    Map<String, Object> fieldMap = new HashMap<String, Object>();
    List<Multipart> multipartList = new ArrayList<Multipart>();
    // 获取并遍历表单项
    List<FileItem> fileItemList;
    try {
        fileItemList = fileUpload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // 异常转换(抛出自定义异常)
        throw new UploadException(e);
    }
    for (FileItem fileItem : fileItemList) {
        // 分两种情况处理表单项
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // 处理普通字段
            String fieldValue = fileItem.getString(FrameworkConstant.UTF_8);
            fieldMap.put(fieldName, fieldValue);
        } else {
            // 处理文件字段
            String fileName = FileUtil.getRealFileName(fileItem.getName());
            if (StringUtil.isNotEmpty(fileName)) {
                long fileSize = fileItem.getSize();
                String contentType = fileItem.getContentType();
                InputStream inputSteam = fileItem.getInputStream();
                // 创建 Multipart 对象,并将其添加到 multipartList 中
                Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam);
                multipartList.add(multipart);
            }
        }
    }
    // 初始化参数列表
    paramList.add(new Params(fieldMap));
    paramList.add(new Multiparts(multipartList));
    // 返回参数列表
    return paramList;
}
 
Example 9
Source File: AdminPageJspBean.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Processes the creation of a child page to the page whose identifier is stored in the http request
 *
 * @param request
 *            The http request
 * @return The jsp url result of the process
 * @throws AccessDeniedException
 *             If the security token is invalid
 */
public String doCreateChildPage( HttpServletRequest request ) throws AccessDeniedException
{
    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;

    String strParentPageId = mRequest.getParameter( Parameters.PAGE_ID );
    int nParentPageId = Integer.parseInt( strParentPageId );

    Page page = new Page( );
    page.setParentPageId( nParentPageId );

    String strErrorUrl = getPageData( mRequest, page );

    if ( strErrorUrl != null )
    {
        return strErrorUrl;
    }
    if ( !SecurityTokenService.getInstance( ).validate( mRequest, TEMPLATE_ADMIN_PAGE_BLOCK_CHILDPAGE ) )
    {
        throw new AccessDeniedException( ERROR_INVALID_TOKEN );
    }

    // Create the page
    _pageService.createPage( page );

    // set the authorization node
    if ( page.getNodeStatus( ) != 0 )
    {
        Page parentPage = PageHome.getPage( page.getParentPageId( ) );
        page.setIdAuthorizationNode( parentPage.getIdAuthorizationNode( ) );
    }
    else
    {
        page.setIdAuthorizationNode( page.getId( ) );
    }

    FileItem item = mRequest.getFile( PARAMETER_IMAGE_CONTENT );

    byte [ ] bytes = item.get( );
    String strMimeType = item.getContentType( );

    page.setImageContent( bytes );
    page.setMimeType( strMimeType );

    _pageService.updatePage( page );

    // Displays again the current page with the modifications
    return getUrlPage( page.getId( ) );
}
 
Example 10
Source File: podHomeBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
	 * Creates a BufferedInputStream to get ready to upload file selected. Used
	 * by Add Podcast and Revise Podcast pages.
	 * 
	 * @param event
	 *            ValueChangeEvent object generated by selecting a file to
	 *            upload.
	 *            
	 * @throws AbortProcessingException
	 * 			Internal processing error attempting to set up BufferedInputStream
	 */
	public void processFileUpload(ValueChangeEvent event)
			throws AbortProcessingException {
		UIComponent component = event.getComponent();

		Object newValue = event.getNewValue();
		Object oldValue = event.getOldValue();
		PhaseId phaseId = event.getPhaseId();
		Object source = event.getSource();
//		log.info("processFileUpload() event: " + event
//				+ " component: " + component + " newValue: " + newValue
//				+ " oldValue: " + oldValue + " phaseId: " + phaseId
//				+ " source: " + source);

		if (newValue instanceof String)
			return;
		if (newValue == null)
			return;

		FileItem item = (FileItem) event.getNewValue();
		String fieldName = item.getFieldName();
		filename = FilenameUtils.getName(item.getName());
		fileSize = item.getSize();
		fileContentType = item.getContentType();
//		log.info("processFileUpload(): item: " + item
//				+ " fieldname: " + fieldName + " filename: " + filename
//				+ " length: " + fileSize);

		// Read the file as a stream (may be more memory-efficient)
		try {
			fileAsStream = new BufferedInputStream(item.getInputStream());
			
		} 
		catch (IOException e) {
			log.warn("IOException while attempting to set BufferedInputStream to upload "
							+ filename + " from site " + podcastService.getSiteId() + ". "
									 + e.getMessage(), e);
			setErrorMessage(INTERNAL_ERROR_ALERT);

		}

	}
 
Example 11
Source File: UpdateServlet.java    From database with GNU General Public License v2.0 2 votes vote down vote up
private boolean validateItem(
		final HttpServletResponse resp, final FileItem item) 
			throws IOException {
	
	final String contentType = item.getContentType();
	
    if (contentType == null) {
    	
        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Content-Type not specified");

        return false;
        
    }

       final RDFFormat format = RDFFormat
               .forMIMEType(new MiniMime(contentType).getMimeType());

    if (format == null) {

        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Content-Type not recognized as RDF: " + contentType);

        return false;

    }
    
       final RDFParserFactory rdfParserFactory = RDFParserRegistry
	        .getInstance().get(format);
	
	if (rdfParserFactory == null) {
	
	    buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN,
	            "Parser factory not found: Content-Type=" + contentType
	                    + ", format=" + format);
	
	    return false;
	
	}

    if (item.getInputStream() == null) {
    	
        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "No content");

        return false;
    	
    }
    
    return true;
	
}