将base64转换为Multipart / Form-data

时间:2018-10-13 08:03:54

标签: javascript ajax spring-boot base64 multipartform-data

我一直在努力将创建的图像上传到项目目录。我使用画布创建了图像,并且希望将图片保存在项目目录中。这是我的代码。

function takeSnapshot() {
    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/jpeg', 0.5);
    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("yes");
        },
        error: (e) => {
            alert("no");
        }
    });
}

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

我正在尝试将base 64转换为multipart / form-data以发送图像。当我使用表格上传时,它可以工作。但是我想知道如何在这里使用它。

这是我的控制器,用于接收传递的文件。

@PostMapping("/api/file/upload")
    public String uploadMultipartFile(@RequestParam("uploadfile") MultipartFile file) {
        try {
            fileStorage.store(file);
            return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
        } catch (Exception e) {
            return "Error -> message = " + e.getMessage();
        }    
    }

有什么我可以做的。当我运行ajax时,它甚至不显示任何错误消息。请帮忙。非常感谢

0 个答案:

没有答案