在Response中发送包含blob的实体对象

时间:2017-06-28 15:09:30

标签: java json spring-boot blob httpresponse

我正在尝试创建一个springboot用户管理应用程序。

我有一个包含两个blob元素的实体对象。这是我的实体对象。

 @Entity
    @Table(name="user_meta_profile")
    public class UserMetaProfile implements Serializable {
        private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "user_id")
    private int user_id;

    @Column(name = "resume_file")
    @Lob
    private Blob resume_file;

    @Column(name = "photo")
    @Lob
    private Blob photo;

    @Column(name = "username")
    private String username;

    public int getUser_id() {
        return user_id;
    }

    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }

    public Blob getResume_file() {
        return resume_file;
    }

    public void setResume_file(Blob resume_file) {
        this.resume_file = resume_file;
    }

    public Blob getPhoto() {
        return photo;
    }

    public void setPhoto(Blob photo) {
        this.photo = photo;
    }

   public void setUsername(String username) {
        this.username = username;
    }
}

正如您所看到的,有两个blob项目' resume_file'和'照片'。

我想向API调用发送一个JSON响应。

我的控制器代码如下所示。

 @Controller
    @RequestMapping("/v1")
    public class UsersController {

    @Autowired 
        private IUserMetaProfileService userMetaProfileService;


    @GetMapping("MetaProfile/{id}")
        public ResponseEntity<UserMetaProfile> getUserMetaProfileById(@PathVariable("id") Integer id) {
            UserMetaProfile userMetaProfile = userMetaProfileService.getUsersById(id);
            return new ResponseEntity<UserMetaProfile>(userMetaProfile, HttpStatus.OK);
        }

    }

但是当我调用API时,我得到了例外:

"exception": "org.springframework.http.converter.HttpMessageNotWritableException",

 "message": "Could not write JSON document: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain:
...

   ...nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

1 个答案:

答案 0 :(得分:1)

由于JSON不能包含二进制数据,因此您需要将这些字段序列化为其他字段。你有几个选择:

  1. 如果您打算将二进制文件显示为图像(因为您的图片是照片),您可以将其序列化为数据uri。
  2. 发送指向照片的链接并创建一个控制器方法,该方法将输出具有相应内容类型的二进制数据(超出此处的范围)。
  3. 因此,对于选项1,您可以执行以下操作:

    @Entity
    @Table(name="user_meta_profile")
    public class UserMetaProfile implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @Column(name = "user_id")
        private int user_id;
    
        @Column(name = "resume_file")
        @Lob
        private Blob resume_file;
    
        @Column(name = "photo")
        @Lob
        private Blob photo;
    
        @Column(name = "username")
        private String username;
    
        public int getUser_id() {
            return user_id;
        }
    
        public void setUser_id(int user_id) {
            this.user_id = user_id;
        }
    
        @JsonIgnore // disable serializing this field by default
        public Blob getResume_file() {
            return resume_file;
        }
    
        // serialize as data uri insted
        @JsonProperty("resumeData")
        public String getResume() {
          // just assuming it is a word document. you would need to cater for different media types
          return "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64," + new String(Base64.getEncoder().encode(resume_file.getBytes()));
        }
    
        public void setResume_file(Blob resume_file) {
            this.resume_file = resume_file;
        }
    
        @JsonIgnore // disable this one too
        public Blob getPhoto() {
            return photo;
        }
    
        // serialize as data uri instead
        @JsonProperty("photoData")
        public String getPhotoBase64() {
          // just assuming it is a jpeg. you would need to cater for different media types
          return "data:image/jpeg;base64," + new String(Base64.getEncoder().encode(photo.getBytes()));
        }
    
        public void setPhoto(Blob photo) {
            this.photo = photo;
        }
    
       public void setUsername(String username) {
            this.username = username;
        }
    }
    

    对于照片位,photoData JSON属性的值可以直接设置为src标记的img属性,照片将在HTML中呈现。使用简历文件,您可以将其作为href附加到<a>标记,并带有download属性,以便下载:

    <a href={photoData value here} download>Download Resume File</a>
    

    就像FYI一样,如果文件很大,JSON会很大,也可能会降低浏览器的速度。