我想将MultipartFile转换为所需的字节类型[],但出现错误

来源:爱站网时间:2021-09-25编辑:网友分享
我正在使用Spring Boot使用Spring Data-Jpa。我有一个由多个部分组成的表单,用于将文件上载到具有其他字段的文件中,例如(firstName,lastName,email,resume等。)但是我一直在获取...

问题描述


我正在使用Spring Boot使用Spring Data-Jpa。我有一个包含多个部分的表单,用于将文件上传到数据库中,并带有其他字段,例如(firstName,lastName,email,resume等)。但是我不断收到此错误消息,将多部分文件转换为所需的byte []类型。如何将pdf文件从多部分文件转换为byte []类型?

这里是myControllerClass

@RequestMapping(value = "/jobs/applyJob/{id}", method = RequestMethod.POST)
public String handleFormSubmit(@PathVariable Long id, @ModelAttribute @Valid Candidate candidate,
        BindingResult bindingResult, @RequestParam("resume") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    Job job = jobService.findJob(id);
    candidate.setJob(job);
    if (file.isEmpty()) {
        return null;
    }
    try {
        byte[] content  = file.getBytes();
        Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
        Files.write(path, content);


    } catch (IOException e) {
        e.printStackTrace();
    }

    if (bindingResult.hasErrors()) {
        return "applyJob";
    }

    redirectAttributes.addFlashAttribute("message", "Job applied !");
    return "redirect:/jobs";
}

我的实体:

@Entity
@Table(name = "candidates")
public class Candidate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty
    @Column(name = "first_name", length = 50)
    private String firstName;

    @NotEmpty
    @Column(name = "last_name", length = 50)
    private String lastName;

    @NotEmpty
    @Column(name = "email", length = 100)
    private String email;

    @NotEmpty
    @Column(name = "phone", length = 15)
    private String phone;

    @NotEmpty
    @Column(name = "address", length = 255)
    private String address;

    @NotEmpty
    @Column(name = "thoughts_on_job", length = 255)
    private String thoughtsOnJob;

    @NotEmpty
    @Column(name = "resume")
    @Lob
    private byte[] resume;

我的错误:

无法转换类型的属性值org.springframework.web.multipart.support.StandardMultipartHttpServletRequest $ StandardMultipartFile属性恢复为必需的类型byte [];嵌套异常为java.lang.IllegalArgumentException:无法转换类型的值org.springframework.web.multipart.support.StandardMultipartHttpServletRequest $ StandardMultipartFile到属性恢复[0]所需的类型字节:PropertyEditor[org.springframework.beans.propertyeditors.CustomNumberEditor]返回类型的不合适值org.springframework.web.multipart.support.StandardMultipartHttpServletRequest $ StandardMultipartFile

思路:


[下面是一个示例示例(使用hibernate / jpa的春季启动),用于将图像数据作为字节[](lob / blob)持久存储到mysql数据库中:

控制器:

public ResponseEntity> uploadFile(@NotBlank @PathVariable String userId,
                                    @RequestParam(value = "profileType", defaultValue = "LOGO", required = false) String profileType,
                                    @RequestParam("avatarFile") MultipartFile avatarFile) {
    return userService.storeFile(user, profileType, avatarFile);
 }

服务:

 @Override
public userImageData storeFile(user user, String profileType, MultipartFile file) {
    log.debug(String.format("Executing  userAvatarOp  = imageDataRepository.findByuserImageDatauserEqualsAndImageTypeEquals(user, profileType);


            if(userAvatarOp.isPresent()){
                userAvatar = userAvatarOp.get();
            }

            userAvatar.setuserImageDatauser(user);
            userAvatar.setImageType(profileType);
            userAvatar.setFileName(fileName);
            userAvatar.setFileType(file.getContentType());
            userAvatar.setData(file.getBytes());
            userAvatar.setFileSize(file.getSize());
            userAvatar.setUploadId(UUID.randomUUID().toString());

            return imageDataRepository.save(userAvatar);
        } catch (IOException ex) {
            throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }
    log.error("Invalid user image data. Please try again!");
    return null;
}

Pojo:

@Entity
@Table(name = "user_avatar")
public class userImageData {

@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "user_avatar_Id")
private String userImageId;

@ManyToOne
@JoinColumn(name = "user_id")
@JsonIgnore
private user userImageDatauser;

private String imageType;
private String fileName;
private String fileType;
private Long fileSize;
@Lob
private byte[] data;
@Transient
private String fileAccessUri;

@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private String uploadId;

}

上一篇:将所有TINYINT字段转换为jooq中的INTEGER

下一篇:执行插入操作时获取SQL语法异常

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载