当前位置: 首页>>代码示例>>Java>>正文


Java CommonsMultipartFile.getSize方法代码示例

本文整理汇总了Java中org.springframework.web.multipart.commons.CommonsMultipartFile.getSize方法的典型用法代码示例。如果您正苦于以下问题:Java CommonsMultipartFile.getSize方法的具体用法?Java CommonsMultipartFile.getSize怎么用?Java CommonsMultipartFile.getSize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.web.multipart.commons.CommonsMultipartFile的用法示例。


在下文中一共展示了CommonsMultipartFile.getSize方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doUploadImageAjax

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
/**
 * Upload an image using AJAX. The response will be returned as JSON object.
 *
 * @param request
 *            the servlet request
 * @param userId
 *            the ID of the user whose image will be updated
 * @return the JSON response object
 */
private ObjectNode doUploadImageAjax(HttpServletRequest request, Long userId) {

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    String errorMessage = null;
    if (cFile != null && cFile.getSize() > 0) {
        if (cFile.getSize() < getMaxUploadSize()) {
            errorMessage = storeImage(request, cFile, userId);
        } else {
            errorMessage = MessageHelper.getText(request, "user.profile.upload.filesize.error",
                    new Object[] { FileUtils.byteCountToDisplaySize(getMaxUploadSize()) });
        }
    } else {
        errorMessage = MessageHelper.getText(request, "user.profile.upload.empty.image");
    }
    if (errorMessage != null) {
        return JsonRequestHelper.createJsonErrorResponse(errorMessage);
    }
    return JsonRequestHelper.createJsonSuccessResponse(null, createSuccessResult(userId));
}
 
开发者ID:Communote,项目名称:communote-server,代码行数:30,代码来源:UserProfileActionController.java

示例2: handleUploadClientLogo

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
/**
 * Handle upload client logo.
 *
 * @param request
 *            the request
 * @param errors
 *            the errors
 * @param form
 *            the form backing object
 * @return the model and view
 */
private ModelAndView handleUploadClientLogo(HttpServletRequest request, BindException errors,
        ClientProfileLogoForm form) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    if (cFile == null || cFile.getSize() <= 0) {
        MessageHelper.saveErrorMessageFromKey(request,
                "client.change.logo.image.upload.empty.image");
        return null;
    }
    ModelAndView mav = null;
    long maxUploadSize = Long.parseLong(CommunoteRuntime.getInstance()
            .getConfigurationManager().getApplicationConfigurationProperties()
            .getProperty(ApplicationProperty.IMAGE_MAX_UPLOAD_SIZE));
    if (cFile.getSize() < maxUploadSize) {
        try {
            byte[] dataLarge = cFile.getBytes();
            ServiceLocator.instance().getService(ConfigurationManagement.class)
                    .updateClientLogo(dataLarge);
            MessageHelper
                    .saveMessageFromKey(request, "client.change.logo.image.upload.success");
            ServiceLocator.findService(ImageManager.class).imageChanged(
                    ClientImageDescriptor.IMAGE_TYPE_NAME,
                    ClientImageProvider.PROVIDER_IDENTIFIER, ClientHelper.getCurrentClientId());
            form.setCustomClientLogo(true);
            mav = new ModelAndView(getSuccessView(), getCommandName(), form);
        } catch (Exception e) {
            LOGGER.error("image upload failed", e);
            String errorMsgKey = getImageUploadExceptionErrorMessageKey(e);
            MessageHelper
                    .saveErrorMessage(request, MessageHelper.getText(request, errorMsgKey));
        }
    } else {
        MessageHelper.saveErrorMessageFromKey(request,
                "client.change.logo.image.upload.filesize.error");
    }
    return mav;
}
 
开发者ID:Communote,项目名称:communote-server,代码行数:49,代码来源:ClientProfileController.java

示例3: isValid

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
public boolean isValid(Object obj, ConstraintValidatorContext context) {
	CommonsMultipartFile file = (CommonsMultipartFile) obj;
	
	if (file != null) {
		if (file.getSize() > 2000000) {
			context.disableDefaultConstraintViolation();
			context.buildConstraintViolationWithTemplate(messageService.getMessageFromResource(request, "config.error.maxUploadSize")).addConstraintViolation();
			return false;
		}
	}
	
	return true;
}
 
开发者ID:thiagoandrade6,项目名称:pubanywhere,代码行数:14,代码来源:MaxSizeUploadValidator.java

示例4: validateFiles

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
/**
 * Control whether the uploaded files are of HTML type and whether their
 * size is under the maxFileSize limit.
 *
 * @param uploadAuditSetUpCommand
 * @param errors
 */
private void validateFiles(AuditSetUpCommand uploadAuditSetUpCommand, Errors errors) {
    boolean emptyFile = true;
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime = null;

    for (int i=0;i<uploadAuditSetUpCommand.getFileInputList().length;i++ ) {
        try {
            CommonsMultipartFile cmf = uploadAuditSetUpCommand.getFileInputList()[i];
            if (cmf.getSize() > maxFileSize) {
                Long maxFileSizeInMega = maxFileSize / 1000000;
                String[] arg = {maxFileSizeInMega.toString()};
                errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            }
            if (cmf.getSize() > 0) {
                emptyFile = false;
                mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
                LOGGER.debug("mime  " + mime + "  " +cmf.getOriginalFilename());
                if (!authorizedMimeType.contains(mime)) {
                    errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
                }
            }
        } catch (IOException ex) {
            LOGGER.warn(ex);
            errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
        }
    }
    if(emptyFile) { // if no file is uploaded
        LOGGER.debug("emptyFiles");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                NO_FILE_UPLOADED_MSG_BUNDLE_KEY);
    }
}
 
开发者ID:Tanaguru,项目名称:Tanaguru,代码行数:41,代码来源:UploadAuditSetUpFormValidator.java

示例5: handleRequestInternal

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Locale locale = sessionHandler.getCurrentLocale(request);
    ObjectNode uploadResult = null;
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    String errorMessage = null;
    if (cFile != null && cFile.getSize() > 0) {
        if (cFile.getSize() < getMaxUploadSize()) {
            try {
                // create a binary content TO
                AttachmentTO binContent = new AttachmentStreamTO(cFile.getInputStream(),
                        AttachmentStatus.UPLOADED);
                binContent.setMetadata(new ContentMetadata());
                binContent.getMetadata().setFilename(cFile.getOriginalFilename());
                binContent.setContentLength(cFile.getSize());

                ResourceStoringManagement rsm = ServiceLocator
                        .findService(ResourceStoringManagement.class);
                Attachment attachment = rsm.storeAttachment(binContent);

                // save attachment IDs in session to allow removing attachments that are removed
                // from the note before publishing
                // we do not do this via separate requests because the ownership is not checked
                // when deleting the attachment
                Set<Long> uploadedFiles = CreateBlogPostFeHelper
                        .getUploadedAttachmentsFromSession(request);
                uploadedFiles.add(attachment.getId());
                uploadResult = CreateBlogPostFeHelper.createAttachmentJSONObject(attachment);
            } catch (ResourceStoringManagementException e) {
                errorMessage = getUploadExceptionErrorMessage(request, e, locale);
            }
        } else {
            errorMessage = ResourceBundleManager.instance().getText(
                    "error.blogpost.upload.filesize.limit", locale,
                    FileUtils.byteCountToDisplaySize(getMaxUploadSize()));
        }
    } else {
        errorMessage = ResourceBundleManager.instance().getText(
                "error.blogpost.upload.empty.file", locale);
    }
    ObjectNode jsonResponse;
    if (errorMessage != null) {
        jsonResponse = JsonRequestHelper.createJsonErrorResponse(errorMessage);
    } else {
        jsonResponse = JsonRequestHelper.createJsonSuccessResponse(null, uploadResult);
    }
    return ControllerHelper.prepareModelAndViewForJsonResponse(multipartRequest, response,
            jsonResponse, true);
}
 
开发者ID:Communote,项目名称:communote-server,代码行数:55,代码来源:AttachmentUploadController.java

示例6: addOrganisation

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
/**
 * Add (or update) an organisation)
 *
 * @param companyId the company id
 * @param userId the user id
 * @param groupId the group id
 * @param owner the owner of the organisation
 * @param name the organisation name
 * @param holder the holder of the organisation
 * @param descr the description of the organisation
 * @param legalStatus the legal status  of the organisation
 * @param street the street address of the organisation's contact
 * @param streetNumber the street number of the organisation's contact
 * @param city the city of the organisation's contact
 * @param country the country of the organisation's contact
 * @param zip the zip of the organisation's contact
 * @param tel the telephone number of the organisation's contact
 * @param fax the fax of the organisation's contact
 * @param mail the email address of the organisation's contact
 * @param web the URL of the organisation's contact
 * @param logo the logo of the organisation (or null)
 * @return the organisation added or changed
 */
public static AHOrg addOrganisation(final long companyId,
        final long userId, final long groupId, final String owner,
        final String name,
        final String holder, final String descr, final String legalStatus,
        final String street,
        final String streetNumber, final String city, final String country,
        final String zip,
        final String tel, final String fax, final String mail,
        final String web, final CommonsMultipartFile logo, float coordsLat, float coordsLon) {
	AHOrg result = null;

	String countryName = country;

	try {
		final Long countryId = Long.parseLong(country);
		final AHCategories countryCat = AHCategoriesLocalServiceUtil
		        .getCategory(countryId);
		if (countryCat != null) {
			countryName = countryCat.getName();
		}
	} catch (final Throwable t) {
		//m_objLog.warn(t);
	}

	final AHRegion region = AHRegionLocalServiceUtil.addRegion(city,
	        countryName,
	        zip);
	final AHAddr address = AHAddrLocalServiceUtil.addAddress(street,
	        streetNumber, null, null, region.getRegionId());
	final AHContact contact = AHContactLocalServiceUtil.addContact(null,
	        null,
	        tel, fax, mail, web);
	// m_objLog.info("Trying to add/update an org for "+owner+" with name "+name);
	result = AHOrgLocalServiceUtil.addOrganisation(owner, name, holder,
	        descr,
	        legalStatus, address.getAddrId(), contact.getContactId());

	if (userId > 0 && result != null && logo != null && logo.getSize() > 0) {
		final String logoLocation = updateLogo(companyId, userId, groupId,
		        result.getOrgId(), logo);
		if (logoLocation != null) {
			AHOrgLocalServiceUtil.updateLogoLocation(result.getOrgId(),
			        logoLocation);
		}
	}
	return result;
}
 
开发者ID:fraunhoferfokus,项目名称:particity,代码行数:71,代码来源:CustomOrgServiceHandler.java

示例7: checkScenarioFileTypeAndSize

import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入方法依赖的package包/类
/**
 * 
 * @param addScenarioCommand
 * @param errors 
 * @return  whether the scenario handled by the current AddScenarioCommand
 * has a correct type and size
 */
public boolean checkScenarioFileTypeAndSize(
        AddScenarioCommand addScenarioCommand, 
        Errors errors) {
    if (addScenarioCommand.getScenarioFile() == null) { // if no file uploaded
        LOGGER.debug("empty Scenario File");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                MANDATORY_FIELD_MSG_BUNDLE_KEY);
        errors.rejectValue(SCENARIO_FILE_KEY,
                NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
        return false;
    }
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime;
    try {
        CommonsMultipartFile cmf = addScenarioCommand.getScenarioFile();
        if (cmf.getSize() > maxFileSize) {
            Long maxFileSizeInMega = maxFileSize / 1000000;
            String[] arg = {maxFileSizeInMega.toString()};
            errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                    MANDATORY_FIELD_MSG_BUNDLE_KEY);
            errors.rejectValue(SCENARIO_FILE_KEY, FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            return false;
        } else if (cmf.getSize() > 0) {
            mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
            LOGGER.debug("mime  " + mime + "  " + cmf.getOriginalFilename());
            if (!authorizedMimeType.contains(mime)) {
                errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                    MANDATORY_FIELD_MSG_BUNDLE_KEY);
                errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
                return false;
            }
        } else {
            LOGGER.debug("File with size null");
            errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                MANDATORY_FIELD_MSG_BUNDLE_KEY);
            errors.rejectValue(SCENARIO_FILE_KEY,
                NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
            return false;
        }
    } catch (IOException ex) {
        LOGGER.warn(ex);
        errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
        errors.rejectValue(GENERAL_ERROR_MSG_KEY,
                MANDATORY_FIELD_MSG_BUNDLE_KEY);
        return false;
    }
    return true;
}
 
开发者ID:Tanaguru,项目名称:Tanaguru,代码行数:57,代码来源:AddScenarioFormValidator.java


注:本文中的org.springframework.web.multipart.commons.CommonsMultipartFile.getSize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。