Javascript 使用 FormData 上传 base64 编码的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26667820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:13:02  来源:igfitidea点击:

Upload a base64 encoded image using FormData?

javascriptform-data

提问by user1031947

I have a jpeg as a base64 encoded string.

我有一个 jpeg 作为 base64 编码的字符串。

var image = "/9j/4AAQSkZJRgABAQEAS..."

I would like to upload this jpeg to the server using FormData.

我想使用 FormData 将此 jpeg 上传到服务器。

var data = new FormData();

What is the proper way to append the image to data?

将图像附加到数据的正确方法是什么?

采纳答案by HeadCode

Your image data is nothing more than a string, so append it to your FormData object like this:

您的图像数据只不过是一个字符串,因此将其附加到您的 FormData 对象中,如下所示:

data.append("image_data", image);

Then on your server side you can store that directly in a database or convert it to an image and store it on the file system. You might find this posthelpful.

然后在您的服务器端,您可以将其直接存储在数据库中或将其转换为图像并将其存储在文件系统中。您可能会发现这篇文章很有帮助。

回答by Kevin

I found this post (Convert Data URI to File then append to FormData) to be quite helpful. If your file is already represented as a base64 encoded string, you would first need to create a blob representation from that and thenyou can use FormData append.

我发现这篇文章(将数据 URI 转换为文件然后附加到 FormData)非常有帮助。如果您的文件已经表示为 base64 编码的字符串,您首先需要从中创建一个 blob 表示,然后您可以使用 FormData 附加。

回答by DINESH Adhikari

 var imgBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCA..." //your bse64 image

onSubmit(){
const file = DataURIToBlob(imgBase64)
const formData = new FormData();
formData.append('upload', file, 'image.jpg') 
formData.append('profile_id', this.profile_id) //other param
formData.append('path', 'temp/') //other param
}

    function DataURIToBlob(dataURI: string) {
        const splitDataURI = dataURI.split(',')
        const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
        const mimeString = splitDataURI[0].split(':')[1].split(';')[0]

        const ia = new Uint8Array(byteString.length)
        for (let i = 0; i < byteString.length; i++)
            ia[i] = byteString.charCodeAt(i)

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