通过AJAX将画布图像作为mulitpart / form-data发送到控制器

时间:2018-10-11 23:36:24

标签: ajax spring canvas multipartform-data

我正在尝试使用带有multipart / form-data的ajax发送画布图像,但是它不起作用。我尝试将其附加到表单数据中,但它甚至不返回错误消息。

这是我的代码:

    var video = document.querySelector('video')
      , canvas;

    var img = document.querySelector('img') || document.createElement('img');
    var context;
    var width = video.offsetWidth
        , height = video.offsetHeight;

    canvas = canvas || document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, width, height);

    img.src = canvas.toDataURL('image/png');
    document.body.appendChild(img);

    var dataURL = canvas.toDataURL('image/png');
    var blob = dataURItoBlob(dataURL);
    var fd = new FormData(document.forms[0]);
    fd.append("canvasImage", blob);

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/api/file/upload",
        data: fd,
        processData: false, //prevent jQuery from automatically transforming the data into a query string
        contentType: false,
        cache: false,
        success: (data) => {
            alert("shit");
        },
        error: (e) => {
            alert("error");
        }
    });

控制器:

@PostMapping("/api/file/upload")
public String uploadMultipartFile(MultipartFile file) {
        return "Content Type RC: " + file.getContentType() + " Name RC: " + file.getName() + "to String: " + file.toString();
}

0 个答案:

没有答案