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

The following examples show how to use org.springframework.web.multipart.MultipartFile#getBytes() . 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: UploadController.java    From spring-boot-projects with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        return "上传失败";
    }
    String fileName = file.getOriginalFilename();
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    //生成文件名称通用方法
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    StringBuilder tempName = new StringBuilder();
    tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
    String newFileName = tempName.toString();
    try {
        // 保存文件
        byte[] bytes = file.getBytes();
        Path path = Paths.get(FILE_UPLOAD_PATH + newFileName);
        Files.write(path, bytes);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "上传成功,图片地址为:/files/" + newFileName;
}
 
Example 2
Source File: UserController.java    From C4SG-Obsolete with MIT License 6 votes vote down vote up
@RequestMapping(value = "/{id}/uploadResume", method = RequestMethod.POST)
@ApiOperation(value = "Add new upload resume")
public String uploadResume(@ApiParam(value = "user Id", required = true) @PathVariable("id") Integer id,
		@ApiParam(value = "Resume File(.pdf)", required = true) @RequestPart("file") MultipartFile file) {

	String contentType = file.getContentType();
	if (!FileUploadUtil.isValidResumeFile(contentType)) {
		return "Invalid pdf File! Content Type :-" + contentType;
	}
	File directory = new File(RESUME_UPLOAD.getValue());
	if (!directory.exists()) {
		directory.mkdir();
	}
	File f = new File(userService.getResumeUploadPath(id));
	try (FileOutputStream fos = new FileOutputStream(f)) {
		byte[] fileByte = file.getBytes();
		fos.write(fileByte);
		return "Success";
	} catch (Exception e) {
		return "Error saving resume for User " + id + " : " + e;
	}
}
 
Example 3
Source File: UploadMultipleFileController.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
private String uploadIndividualFile(File dir, MultipartFile multipartFile, Model model, MultipleFilesUploadForm multipleFileUploadForm){
	try {
		byte[] bytes = multipartFile.getBytes();

		// accesses the file from the source folder and copies it to the repository
		File serverFile = new File(dir.getAbsolutePath()
				+ File.separator
				+ multipartFile.getOriginalFilename());
		BufferedOutputStream stream = new BufferedOutputStream(
				new FileOutputStream(serverFile));
		stream.write(bytes);
		stream.close();
           return "view_files_form";
	} catch (Exception e) {
		model.addAttribute("multipleFileUploadForm", multipleFileUploadForm);
		return "upload_multiple_form";
		
	}
}
 
Example 4
Source File: UploadController.java    From spring-boot-cookbook with Apache License 2.0 6 votes vote down vote up
@PostMapping//new annotation since 4.3
public String upload(@RequestParam("file") MultipartFile file,
                     RedirectAttributes redirectAttributes) {
    uploadService.countUploadFiles();
    String globalMsg = "globalMsg";
    if (file.isEmpty()) {
        redirectAttributes.addFlashAttribute(globalMsg, "choose a file to upload");
        return "redirect:/test/upload";
    }
    try {
        byte[] bytes = file.getBytes();
        String filename = file.getOriginalFilename();
        Path path = Paths.get("/tmp/", filename);
        Files.write(path, bytes);
        file.transferTo(Paths.get("/tmp/", "bak_" + filename).toFile());
        String savePath = path.toFile().getAbsolutePath();
        LOGGER.info(savePath);
        redirectAttributes.addFlashAttribute(globalMsg, "success to upload " + filename + ",\n save to " + savePath);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        redirectAttributes.addFlashAttribute(globalMsg, e.getMessage());
    }

    return "redirect:/test/upload";
}
 
Example 5
Source File: UserController.java    From C4SG-Obsolete with MIT License 6 votes vote down vote up
@RequestMapping(value = "/{id}/uploadAvatar", method = RequestMethod.POST)
@ApiOperation(value = "Add new upload Avatar")
public String uploadAvatar(@ApiParam(value = "user Id", required = true) @PathVariable("id") 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(AVATAR_UPLOAD.getValue());
	if (!directory.exists()) {
		directory.mkdir();
	}
	File f = new File(userService.getAvatarUploadPath(id));
	try (FileOutputStream fos = new FileOutputStream(f)) {
		byte[] imageByte = file.getBytes();
		fos.write(imageByte);
		return "Success";
	} catch (Exception e) {
		return "Error saving avatar for User " + id + " : " + e;
	}
}
 
Example 6
Source File: ByteArrayMultipartFileEditor.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void setValue(@Nullable Object value) {
	if (value instanceof MultipartFile) {
		MultipartFile multipartFile = (MultipartFile) value;
		try {
			super.setValue(multipartFile.getBytes());
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Cannot read contents of multipart file", ex);
		}
	}
	else if (value instanceof byte[]) {
		super.setValue(value);
	}
	else {
		super.setValue(value != null ? value.toString().getBytes() : null);
	}
}
 
Example 7
Source File: MsgSettingServiceImpl.java    From CheckPoint with Apache License 2.0 5 votes vote down vote up
/**
 * Update from file.
 *
 * @param file the file
 */
public void updateFromFile(MultipartFile file) {
    ObjectMapper objectMapper = ValidationObjUtil.getDefaultObjectMapper();

    try {
        String jsonStr = new String(file.getBytes(), "UTF-8");
        List<ValidationData> list = objectMapper.readValue(jsonStr, objectMapper.getTypeFactory().constructCollectionType(List.class, ValidationData.class));
        List<ReqUrl> reqUrls = ValidationReqUrlUtil.getUrlListFromValidationDatas(list);
        reqUrls.forEach(reqUrl -> {
            this.deleteValidationData(reqUrl);
        });
        Map<Long, Long> idsMap = new HashMap<>();
        List<ValidationData> saveList = new ArrayList<>();

        list.forEach(data -> {
            long oldId = data.getId();
            data.setId(null);
            data = this.validationDataRepository.save(data);
            idsMap.put(oldId, data.getId());
            saveList.add(data);
        });

        saveList.forEach(data -> {
            if (data.getParentId() != null) {
                data.setParentId(idsMap.get(data.getParentId()));
                this.validationDataRepository.save(data);
            }
        });

    } catch (IOException e) {
        log.info("file io exception : " + e.getMessage());
    }
}
 
Example 8
Source File: TacInstController.java    From tac with MIT License 5 votes vote down vote up
@PostMapping(value = "/prePublish")
public TacResult<TacInst> prePublish(@RequestParam("file") MultipartFile instFileRO,
                                     @RequestParam("msCode") String msCode,
                                     @RequestParam(value = "instId", required = false) Long instId) {

    try {
        byte[] bytes = instFileRO.getBytes();
        String md5 = TacFileService.getMd5(bytes);

        TacMsDO ms = msService.getMs(msCode);
        if (ms == null) {
            throw new IllegalArgumentException("the service is not exist");
        }

        TacInst tacMsInst = this.getExistTacInst(ms, md5);

        // prepublish
        msPublisher.prePublish(tacMsInst, bytes);

        return TacResult.newResult(msInstService.getTacMsInst(tacMsInst.getId()));

    } catch (Exception e) {

        return TacResult.errorResult(ConsoleError.SYSTEM_ERROR.getCode(), e.getMessage());
    }

}
 
Example 9
Source File: TemplateFileController.java    From youran with Apache License 2.0 5 votes vote down vote up
@Override
@PostMapping(value = "/upload")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<TemplateFileShowVO> upload(@RequestParam Integer templateId,
                                                 @RequestParam String fileDir,
                                                 MultipartFile file) throws Exception {
    if (file == null) {
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "文件为空");
    }
    String filename = file.getOriginalFilename();
    if (StringUtils.isBlank(filename)) {
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "文件名为空");
    }
    if (filename.length() > 100) {
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "文件名长度不能超过100");
    }
    byte[] bytes = file.getBytes();
    if (file.getSize() == 0 || ArrayUtils.isEmpty(bytes)) {
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "文件内容不能为空");
    }
    if (file.getSize() > TemplateFilePO.TEMPLATE_FILE_LENGTH_LIMIT) {
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "文件超过最大长度限制:" +
            FileUtils.byteCountToDisplaySize(TemplateFilePO.TEMPLATE_FILE_LENGTH_LIMIT));
    }
    TemplateFilePO templateFile = templateFileService.saveBinary(templateId, fileDir, filename, bytes);
    return ResponseEntity.created(new URI(apiPath + "/template_file/" + templateFile.getFileId()))
        .body(TemplateFileMapper.INSTANCE.toShowVO(templateFile));
}
 
Example 10
Source File: WebuiMailAttachmentsRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public LookupValue createAttachment(@NonNull final String emailId, @NonNull final MultipartFile file)
{
	//
	// Extract the original filename
	String originalFilename = file.getOriginalFilename();
	if (Check.isEmpty(originalFilename, true))
	{
		originalFilename = file.getName();
	}
	if (Check.isEmpty(originalFilename, true))
	{
		throw new AdempiereException("Filename not provided");
	}

	byte[] fileContent;
	try
	{
		fileContent = file.getBytes();
	}
	catch (IOException e)
	{
		throw new AdempiereException("Failed fetching attachment content")
				.setParameter("filename", originalFilename);
	}

	return createAttachment(emailId, originalFilename, fileContent);
}
 
Example 11
Source File: Server.java    From feign-form with Apache License 2.0 5 votes vote down vote up
@RequestMapping(
    path = "/multipart/upload1/{folder}",
    method = POST,
    consumes = MULTIPART_FORM_DATA_VALUE
)
@SneakyThrows
public String upload1 (@PathVariable("folder") String folder,
                       @RequestPart MultipartFile file,
                       @RequestParam(value = "message", required = false) String message
) {
  return new String(file.getBytes()) + ':' + message + ':' + folder;
}
 
Example 12
Source File: UploadController.java    From spring-boot-projects with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Result upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        return ResultGenerator.genFailResult("请选择文件");
    }
    String fileName = file.getOriginalFilename();
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    //生成文件名称通用方法
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    StringBuilder tempName = new StringBuilder();
    tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
    String newFileName = tempName.toString();
    try {
        // 保存文件
        byte[] bytes = file.getBytes();
        Path path = Paths.get(Constants.FILE_UPLOAD_PATH + newFileName);
        Files.write(path, bytes);

    } catch (IOException e) {
        e.printStackTrace();
    }
    Result result = ResultGenerator.genSuccessResult();
    result.setData("files/" + newFileName);
    return result;
}
 
Example 13
Source File: PacController.java    From owlaser-paclist with MIT License 5 votes vote down vote up
@ResponseBody
@PostMapping(value = "/upload")
public Object upload(@RequestParam("file") MultipartFile file) {
    if(!file.getOriginalFilename().equals("pom.xml") && !file.getOriginalFilename().matches(".*\\.jar")){
        return ResponseUtil.badArgument();
    }

    ArrayList<Dependency> dependenciesList = new ArrayList<>();
    try {
        byte[] bytes = file.getBytes();
        String folderPath = "./repository/pom/";
        Path filePath = Paths.get(folderPath + file.getOriginalFilename());
        Files.write(filePath, bytes);
        Pattern r = Pattern.compile("(pom.xml)$");
        Matcher m = r.matcher(file.getOriginalFilename());

        if(!m.find()){
            byte[] pomFile = pacService.JarRead(folderPath + file.getOriginalFilename());
            if(pomFile.length == 1) return ResponseUtil.noPom();
            Files.write(filePath, pomFile);
        }

        String textPath = pacService.CreateDependencyText(folderPath, filePath);
        Node root = DependencyTreeService.GetRoot(textPath);
        pacService.GetDependencies(root, dependenciesList);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Sum_dependency_license sum_dependency_license = new Sum_dependency_license(dependenciesList,licenseService.getConflic(dependenciesList));

    return ResponseUtil.ok(sum_dependency_license);
}
 
Example 14
Source File: VideoController.java    From auto-subtitle-tool with GNU General Public License v2.0 5 votes vote down vote up
private boolean checkFileType(MultipartFile file) throws IOException {
    byte[] content = file.getBytes();
    InputStream is = new BufferedInputStream(new ByteArrayInputStream(content));
    String mimeType = URLConnection.guessContentTypeFromStream(is);
    if(allowedTypes.contains(mimeType))
        return true;
    else
        return false;
}
 
Example 15
Source File: WebIMController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/invote/save")
@Menu(type = "admin" , subtype = "profile" , admin= true)
public ModelAndView saveinvote(HttpServletRequest request , @Valid CousultInvite inviteData, @RequestParam(value = "invotebg", required = false) MultipartFile invotebg) throws IOException {
	CousultInvite tempInviteData  ;
	if(inviteData!=null && !StringUtils.isBlank(inviteData.getId())){
		tempInviteData = invite.findOne(inviteData.getId()) ;
		if(tempInviteData!=null){
			tempInviteData.setConsult_invite_enable(inviteData.isConsult_invite_enable());
			tempInviteData.setConsult_invite_content(inviteData.getConsult_invite_content());
			tempInviteData.setConsult_invite_accept(inviteData.getConsult_invite_accept());
			tempInviteData.setConsult_invite_later(inviteData.getConsult_invite_later());
			tempInviteData.setConsult_invite_delay(inviteData.getConsult_invite_delay());
			
			tempInviteData.setConsult_invite_color(inviteData.getConsult_invite_color());
			
			if(invotebg!=null && !StringUtils.isBlank(invotebg.getName()) && invotebg.getBytes()!=null && invotebg.getBytes().length >0){
 			String fileName = "invote/"+inviteData.getId()+invotebg.getOriginalFilename().substring(invotebg.getOriginalFilename().lastIndexOf(".")) ;
 			File file = new File(path , fileName) ;
 			if(!file.getParentFile().exists()){
 				file.getParentFile().mkdirs();
 			}
     		FileCopyUtils.copy(invotebg.getBytes(), file);
     		tempInviteData.setConsult_invite_bg(fileName);
			}
    		invite.save(tempInviteData) ;
    		inviteData = tempInviteData ;
		}
	}else{
		invite.save(inviteData) ;
	}
	CacheHelper.getSystemCacheBean().put(inviteData.getSnsaccountid(), inviteData, inviteData.getOrgi());
    return request(super.createRequestPageTempletResponse("redirect:/admin/webim/invote.html?snsid="+inviteData.getSnsaccountid()));
}
 
Example 16
Source File: BaseModelSourceResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public byte[] getFileBytes(MultipartFile file) {
    byte[] byteArray = null;
    try {
        byteArray = file.getBytes();
    } catch (Exception e) {
        throw new FlowableException("Error getting file bytes", e);
    }
    return byteArray;
}
 
Example 17
Source File: DocumentAttachments.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public void addEntry(final MultipartFile file) throws IOException
{
	Check.assumeNotNull(file, "Parameter file is not null");
	final String name = file.getOriginalFilename();
	final byte[] data = file.getBytes();

	attachmentEntryService.createNewAttachment(recordRef, name, data);

	notifyRelatedDocumentTabsChanged();
}
 
Example 18
Source File: ApiMigrationRestController.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private String getLocalFilePath(MultipartFile multipartFile) throws IOException {
		String fileName = Paths.get(localM3Files, multipartFile.getOriginalFilename()).toString();
		byte[] bytes = multipartFile.getBytes();
	    java.nio.file.Path path = Paths.get(fileName);
	    Files.write(path, bytes);
	    return fileName;
}
 
Example 19
Source File: UiApplication.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String accept(@RequestParam MultipartFile file) throws IOException {
	return new String(file.getBytes());
}
 
Example 20
Source File: FileBoundary.java    From blog-tutorials with MIT License 3 votes vote down vote up
@PostMapping
public ResponseEntity<Void> uploadNewFile(@NotNull @RequestParam("file") MultipartFile multipartFile) throws IOException {

  FileEntity fileEntity = new FileEntity(multipartFile.getOriginalFilename(), multipartFile.getContentType(),
    multipartFile.getBytes());

  fileEntityRepository.save(fileEntity);

  URI location = ServletUriComponentsBuilder.fromCurrentRequest().build().toUri();
  return ResponseEntity.created(location).build();

}