jQuery.ajax():将blob对象发送到Spring REST

时间:2018-02-03 16:31:22

标签: javascript jquery ajax spring-boot spring-rest

如何通过jQuery.ajax()发送一个包含String和Blob类型的对象,并在Spring REST端通过@RequestBody myModelClass接收它?

JavaScript的:

function savePicture() {

 var img = canvas.toDataURL('image/jpeg');
 var blob = new Blob([img], {type: 'image/jpeg'});
 var d = new Date();
 var cd = (d.getUTCMonth()+1) + "/" + d.getUTCDate() + "/" + d.getUTCFullYear();

 var fd = new FormData();
 fd.append('name', 'mypicture');
 fd.append('author', 'Kate');
 fd.append('createdDate', cd);
 fd.append('content', blob);

 $.ajax({
    type: "POST",
    url: "/send",
    data: fd,
    processData: false,
    contentType: 'application/json',
    cache: false,
    timeout: 600000,
    success: function (data) {
        console.log(data);
    },
    error: function (e) { }
 });

}

Spring REST(从ajax()接收对象并保存到数据库的函数。):

@PostMapping(value="/send")
public ResponseEntity<?> sendPictureToDatabase(@RequestBody Picture picture, Errors errors) throws IOException {

    pictureService.savePicture(picture);
    AjaxResponseBody result = new AjaxResponseBody();
    result.setMsg("success");
    result.setResult(pictureService.getAllPictures());
    return ResponseEntity.ok(result);
}

我的模特:

@Entity
public class Picture {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(nullable=false)
  private Long id;

  @Column(nullable=false)
  private String name;

  @Column(nullable=false)
  private String author;

  @Column(name="CREATED_DATE", nullable=true)
  @Convert(converter = LocalDateAttributeConverter.class)
  private LocalDate createdDate;

  @Column(nullable=false)
  @Lob
  private String[] content;

  //...
}

0 个答案:

没有答案