Java Code Examples for org.springframework.web.multipart.MultipartFile#getContentType()

The following examples show how to use org.springframework.web.multipart.MultipartFile#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: ImageGalleryUtils.java    From lams with GNU General Public License v2.0 8 votes vote down vote up
/**
    * Validate imageGallery item.
    */
   public static MultiValueMap<String, String> validateMultipleImages(MultipleImagesForm multipleForm,
    boolean largeFile, MessageService messageService) {

MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();

List<MultipartFile> fileList = ImageGalleryUtils.createFileListFromMultipleForm(multipleForm);

// validate files size
for (MultipartFile file : fileList) {
    FileValidatorUtil.validateFileSize(file, largeFile);

    // check for allowed format : gif, png, jpg
    String contentType = file.getContentType();
    if (ImageGalleryUtils.isContentTypeForbidden(contentType)) {
	errorMap.add("GLOBAL", messageService.getMessage("error.resource.image.not.alowed.format.for"));
    }
}

return errorMap;
   }
 
Example 2
Source File: UICiDataManagementController.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
@RolesAllowed({ MENU_ADMIN_CMDB_MODEL_MANAGEMENT, MENU_DESIGNING_CI_DATA_MANAGEMENT })
@PostMapping("/ci-types/{ci-type-id}/icon")
@ResponseBody
public Object uploadCiTypeIcon(@PathVariable(value = "ci-type-id") int ciTypeId, @RequestParam(value = "file", required = false) MultipartFile file) throws CmdbException {
    if (file.getSize() > applicationProperties.getMaxFileSize().toBytes()) {
        String errorMessage = String.format("Upload image icon for CiType (%s) failed due to file size (%s bytes) exceeded limitation (%s KB).", ciTypeId, file.getSize(), applicationProperties.getMaxFileSize().toKilobytes());
        log.warn(errorMessage);
        throw new CmdbException(errorMessage);
    }

    try {
        String contentType = file.getContentType();
        return imageService.upload(file.getName(), contentType, file.getBytes());
    } catch (IOException e) {
        String msg = String.format("Failed to upload image file. (fileName:%s)", file.getName());
        log.warn(msg, e);
        throw new CmdbException(msg);
    }
}
 
Example 3
Source File: FileController.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 上传文件
 *
 * @param
 * @return
 * @author zuihou
 * @date 2019-05-06 16:28
 */
@ApiOperation(value = "上传文件", notes = "上传文件 ")
@ApiResponses({
        @ApiResponse(code = 60102, message = "文件夹为空"),
})
@ApiImplicitParams({
        @ApiImplicitParam(name = "folderId", value = "文件夹id", dataType = "long", paramType = "query"),
        @ApiImplicitParam(name = "file", value = "附件", dataType = "MultipartFile", allowMultiple = true, required = true),
})
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@SysLog("上传文件")
public R<File> upload(
        @NotNull(message = "文件夹不能为空")
        @RequestParam(value = "folderId") Long folderId,
        @RequestParam(value = "file") MultipartFile simpleFile) {
    //1,先将文件存在本地,并且生成文件名
    log.info("contentType={}, name={} , sfname={}", simpleFile.getContentType(), simpleFile.getName(), simpleFile.getOriginalFilename());
    // 忽略路径字段,只处理文件类型
    if (simpleFile.getContentType() == null) {
        return fail("文件为空");
    }

    File file = baseService.upload(simpleFile, folderId);

    return success(file);
}
 
Example 4
Source File: OrganizationController.java    From C4SG-Obsolete with MIT License 6 votes vote down vote up
@RequestMapping(value = "/{id}/uploadLogoAsFile", method = RequestMethod.POST)
@ApiOperation(value = "Add new upload Logo as Image File")
public String uploadLogo(@ApiParam(value = "Organization Id", required = true) @PathVariable Integer id,
		@ApiParam(value = "Image File", required = true) @RequestPart("file") MultipartFile file) {

	String contentType = file.getContentType();
	if (!FileUploadUtil.isValidImageFile(contentType)) {
		return "Invalid Image file! Content Type :-" + contentType;
	}
	File directory = new File(LOGO_UPLOAD.getValue());
	if (!directory.exists()) {
		directory.mkdir();
	}
	File f = new File(organizationService.getLogoUploadPath(id));
	try (FileOutputStream fos = new FileOutputStream(f)) {
		byte[] imageByte = file.getBytes();
		fos.write(imageByte);
		return "Success";
	} catch (Exception e) {
		return "Error saving logo for organization " + id + " : " + e;
	}
}
 
Example 5
Source File: AbstractRelatedContentResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected RelatedContentRepresentation uploadFile(User user, MultipartFile file, String taskId, String processInstanceId) {
    if (file != null && file.getName() != null) {
        try {
            String contentType = file.getContentType();
            
            // temp additional content type check for IE9 flash uploads
            if (StringUtils.equals(file.getContentType(), "application/octet-stream")) {
                contentType = getContentTypeForFileExtension(file);
            }
            
            RelatedContent relatedContent = contentService.createRelatedContent(user, getFileName(file), null, null, taskId, processInstanceId, 
                    contentType, file.getInputStream(), file.getSize(), true, false);
            return new RelatedContentRepresentation(relatedContent, simpleTypeMapper);
        } catch (IOException e) {
            throw new BadRequestException("Error while reading file data", e);
        }
    } else {
        throw new BadRequestException("File to upload is missing");
    }
}
 
Example 6
Source File: FileController.java    From mongodb-file-server with MIT License 6 votes vote down vote up
/**
 * 上传
 * 
 * @param file
 * @param redirectAttributes
 * @return
 */
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

	try {
		File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(),
				new Binary(file.getBytes()));
		f.setMd5(MD5Util.getMD5(file.getInputStream()));
		fileService.saveFile(f);
	} catch (IOException | NoSuchAlgorithmException ex) {
		ex.printStackTrace();
		redirectAttributes.addFlashAttribute("message", "Your " + file.getOriginalFilename() + " is wrong!");
		return "redirect:/";
	}

	redirectAttributes.addFlashAttribute("message",
			"You successfully uploaded " + file.getOriginalFilename() + "!");

	return "redirect:/";
}
 
Example 7
Source File: ImageUtils.java    From file-service with Apache License 2.0 6 votes vote down vote up
public static MultipartFile cutImage(MultipartFile file, Double rotate, Integer axisX, Integer axisY, Integer width, Integer height) throws java.io.IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    if (rotate != null) {
        Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).rotate(rotate).toOutputStream(outputStream);
    }
    if (axisX != null && axisY != null && width != null && height != null) {
        if (outputStream.size() > 0) {
            final InputStream rotateInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            outputStream.reset();
            Thumbnails.of(rotateInputStream).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream);
        } else {
            Thumbnails.of(file.getInputStream()).scale(1.0, 1.0).sourceRegion(axisX, axisY, width, height).toOutputStream(outputStream);
        }
    }
    if (outputStream.size() > 0) {
        file = new MockMultipartFile(file.getName(), file.getOriginalFilename(),
                file.getContentType(), outputStream.toByteArray());
    }
    return file;
}
 
Example 8
Source File: MockMultipartHttpServletRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	MultipartFile file = getFile(paramOrFileName);
	if (file != null) {
		return file.getContentType();
	}
	else {
		return null;
	}
}
 
Example 9
Source File: Server.java    From feign-form with Apache License 2.0 5 votes vote down vote up
@RequestMapping(
    path = "/multipart/upload3/{folder}",
    method = POST,
    consumes = MULTIPART_FORM_DATA_VALUE
)
public String upload3 (@RequestBody MultipartFile file,
                       @PathVariable("folder") String folder,
                       @RequestParam(value = "message", required = false) String message
) {
  return file.getOriginalFilename() + ':' + file.getContentType() + ':' + folder;
}
 
Example 10
Source File: IMController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
private String processAttachmentFile(MultipartFile file , HttpServletRequest request) throws IOException{
  	String id = null ;
  	if(file.getSize() > 0){			//文件尺寸 限制 ?在 启动 配置中 设置 的最大值,其他地方不做限制
	String fileid = UKTools.md5(file.getBytes()) ;	//使用 文件的 MD5作为 ID,避免重复上传大文件
	if(!StringUtils.isBlank(fileid)){
  			AttachmentFile attachmentFile = new AttachmentFile() ;
  			attachmentFile.setCreater(super.getUser(request).getId());
  			attachmentFile.setOrgi(super.getOrgi(request));
  			attachmentFile.setOrgan(super.getUser(request).getOrgan());
  			attachmentFile.setModel(UKDataContext.ModelType.WEBIM.toString());
  			attachmentFile.setFilelength((int) file.getSize());
  			if(file.getContentType()!=null && file.getContentType().length() > 255){
  				attachmentFile.setFiletype(file.getContentType().substring(0 , 255));
  			}else{
  				attachmentFile.setFiletype(file.getContentType());
  			}
  			File uploadFile = new File(file.getOriginalFilename());
  			if(uploadFile.getName()!=null && uploadFile.getName().length() > 255){
  				attachmentFile.setTitle(uploadFile.getName().substring(0 , 255));
  			}else{
  				attachmentFile.setTitle(uploadFile.getName());
  			}
  			if(!StringUtils.isBlank(attachmentFile.getFiletype()) && attachmentFile.getFiletype().indexOf("image") >= 0){
  				attachmentFile.setImage(true);
  			}
  			attachmentFile.setFileid(fileid);
  			attachementRes.save(attachmentFile) ;
  			FileUtils.writeByteArrayToFile(new File(path , "app/webim/"+fileid), file.getBytes());
  			id = attachmentFile.getId();
	}
}
  	return id  ;
  }
 
Example 11
Source File: AbstractRelatedContentResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected ContentItemRepresentation uploadFile(User user, MultipartFile file, String taskId, String processInstanceId, String caseId) {
    if (file != null && file.getName() != null) {
        try {
            String contentType = file.getContentType();

            // temp additional content type check for IE9 flash uploads
            if (StringUtils.equals(file.getContentType(), "application/octet-stream")) {
                contentType = getContentTypeForFileExtension(file);
            }

            ContentItem contentItem = contentService.newContentItem();
            contentItem.setName(getFileName(file));
            contentItem.setProcessInstanceId(processInstanceId);
            contentItem.setTaskId(taskId);
            if (StringUtils.isNotEmpty(caseId)) {
                contentItem.setScopeType("cmmn");
                contentItem.setScopeId(caseId);
            }
            contentItem.setMimeType(contentType);
            contentItem.setCreatedBy(user.getId());
            contentItem.setLastModifiedBy(user.getId());
            contentService.saveContentItem(contentItem, file.getInputStream());

            return createContentItemResponse(contentItem);

        } catch (IOException e) {
            throw new BadRequestException("Error while reading file data", e);
        }

    } else {
        throw new BadRequestException("File to upload is missing");
    }
}
 
Example 12
Source File: MockMultipartActionRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	MultipartFile file = getFile(paramOrFileName);
	if (file != null) {
		return file.getContentType();
	}
	else {
		return null;
	}
}
 
Example 13
Source File: FileAction.java    From albert with MIT License 5 votes vote down vote up
@RequestMapping(value = "/uploadAvatar",method = RequestMethod.POST, produces="application/json;charset=utf-8") 
@ResponseBody
public Map<String, Object> uploadHeadPortrait(MultipartFile avatar_file,String avatar_src,String avatar_data, HttpServletRequest request){
	Map<String, Object> json = new HashMap<String, Object>();
	if (!avatar_file.isEmpty()) {
		try{
	        //判断文件的MIMEtype
	        String type = avatar_file.getContentType();
	        if(type == null || !type.toLowerCase().startsWith("image/")){
	        	json = this.setJson(false, "不支持的文件类型,仅支持图片!", null);
	        	return  json;
	        }
			//头像存放文件
			String dir = "avator";
			Map<String, Object> returnMap = UploadFileUtils.Upload(request,avatar_file,avatar_data,dir);
			//返回的布尔型参数的值为true,如果字符串参数不为null,是相等的,忽略大小写字符串“true”。
			if (Boolean.parseBoolean(returnMap.get("flag").toString()) == true) {
				User user =UserSessionUtil.currentUser();
				user.setAvatar(returnMap.get("savaPath").toString());
				userService.updateAvatar(user);
				json = this.setJson(true, "上传成功!", returnMap.get("savaPath").toString());
				System.out.println("存放路径:"+returnMap.get("savaPath").toString());
				return json;
			} 
		}catch(Exception e){
			logger.error("ImageUploadController.uploadHeadPortrait", e);
			json = this.setJson(false, "上传失败,出现异常:"+e.getMessage(), null);
			return json;
		}
	}
   	json = this.setJson(false, "不支持的文件类型,仅支持图片!", null);
   	return  json;
}
 
Example 14
Source File: FileResourceController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@PostMapping
public WebMessage saveFileResource( @RequestParam MultipartFile file,
    @RequestParam( defaultValue = "DATA_VALUE" ) FileResourceDomain domain
)
    throws WebMessageException, IOException
{
    String filename = StringUtils
        .defaultIfBlank( FilenameUtils.getName( file.getOriginalFilename() ), DEFAULT_FILENAME );

    String contentType = file.getContentType();
    contentType = FileResourceUtils.isValidContentType( contentType ) ? contentType : DEFAULT_CONTENT_TYPE;

    long contentLength = file.getSize();

    log.info( "File uploaded with filename: '{}', original filename: '{}', content type: '{}', content length: {}",
        filename, file.getOriginalFilename(), file.getContentType(), contentLength );

    if ( contentLength <= 0 )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Could not read file or file is empty." ) );
    }

    ByteSource bytes = new MultipartFileByteSource( file );

    String contentMd5 = bytes.hash( Hashing.md5() ).toString();

    FileResource fileResource = new FileResource( filename, contentType, contentLength, contentMd5, domain );

    File tmpFile = FileResourceUtils.toTempFile( file );

    fileResourceService.saveFileResource( fileResource, tmpFile );

    WebMessage webMessage = new WebMessage( Status.OK, HttpStatus.ACCEPTED );
    webMessage.setResponse( new FileResourceWebMessageResponse( fileResource ) );

    return webMessage;
}
 
Example 15
Source File: WebuiImageService.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public WebuiImageId uploadImage(final MultipartFile file) throws IOException
{
	final String name = file.getOriginalFilename();
	final byte[] data = file.getBytes();
	final String contentType = file.getContentType();
	final String filenameNorm = normalizeUploadFilename(name, contentType);

	final MImage adImage = new MImage(Env.getCtx(), 0, ITrx.TRXNAME_None);
	adImage.setName(filenameNorm);
	adImage.setBinaryData(data);
	// TODO: introduce adImage.setTemporary(true);
	InterfaceWrapperHelper.save(adImage);

	return WebuiImageId.ofRepoId(adImage.getAD_Image_ID());
}
 
Example 16
Source File: MockMultipartHttpServletRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	MultipartFile file = getFile(paramOrFileName);
	if (file != null) {
		return file.getContentType();
	}
	else {
		return null;
	}
}
 
Example 17
Source File: MockMultipartHttpServletRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	MultipartFile file = getFile(paramOrFileName);
	if (file != null) {
		return file.getContentType();
	}
	else {
		return null;
	}
}
 
Example 18
Source File: MockMultipartHttpServletRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	MultipartFile file = getFile(paramOrFileName);
	if (file != null) {
		return file.getContentType();
	}
	else {
		return null;
	}
}
 
Example 19
Source File: UploadController.java    From karate with MIT License 4 votes vote down vote up
private FileInfo getFileInfo(MultipartFile file, String message) throws Exception {

        String uuid = UUID.randomUUID().toString();
        String filePath = FILES_BASE + uuid;

        FileUtils.copyToFile(file.getInputStream(), new File(filePath));
        String filename1 = file.getOriginalFilename();
        String contentType1 = file.getContentType();

        FileInfo fileInfo = new FileInfo(uuid, filename1, message, contentType1);
        String json = mapper.writeValueAsString(fileInfo);
        FileUtils.writeStringToFile(new File(filePath + "_meta.txt"), json, "utf-8");

        return fileInfo;

    }
 
Example 20
Source File: UpLoadController.java    From FlyCms with MIT License 4 votes vote down vote up
/**
 * 上传图片
 * @param file
 */
@RequestMapping(value = "/ucenter/uploadImage", method = RequestMethod.POST)
@ResponseBody
public CkeditorUp uploadImage(@RequestParam("upload") MultipartFile file)throws Exception {
    if (!file.isEmpty()) {
        String proName = Const.UPLOAD_PATH;
        String path = proName + "/upload/usertmp/"+getUser().getUserId()+"/";
        String fileName = file.getOriginalFilename();
        String uploadContentType = file.getContentType();
        String expandedName = "";
        if ("image/jpeg".equals(uploadContentType)
                || uploadContentType.equals("image/jpeg")) {
            // IE6上传jpg图片的headimageContentType是image/pjpeg,而IE9以及火狐上传的jpg图片是image/jpeg
            expandedName = ".jpg";
        } else if ("image/png".equals(uploadContentType) || "image/x-png".equals(uploadContentType)) {
            // IE6上传的png图片的headimageContentType是"image/x-png"
            expandedName = ".png";
        } else if ("image/gif".equals(uploadContentType)) {
            expandedName = ".gif";
        } else if ("image/bmp".equals(uploadContentType)) {
            expandedName = ".bmp";
        } else {
            return CkeditorUp.failure("文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)");
        }
        if (file.getSize() > 1024 * 1024 * 2) {
            return CkeditorUp.failure("文件大小不得大于2M");
        }

        DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
        fileName = df.format(new Date()) + expandedName;
        File dirFile = new File(path + fileName);
        //判断文件父目录是否存在
        if(!dirFile.getParentFile().exists()){
            dirFile.getParentFile().mkdir();
        }
        imagesService.uploadFile(file.getBytes(), path, fileName);
        int port=request.getServerPort();
        String portstr="";
        if(port>0){
            portstr+=":"+port;
        }
        return CkeditorUp.success(1,fileName,"http://"+ request.getServerName()+portstr+"/upload/usertmp/"+getUser().getUserId() + "/" + fileName);
    } else {
        return CkeditorUp.failure("上传失败");
    }
}