Javascript 如何通过 .ajax 以 base64 编码发布图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34047648/
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-23 15:51:04  来源:igfitidea点击:

How to post an image in base64 encoding via .ajax?

javascriptjqueryajax

提问by carbontracking

I have some javascript code that uploads an image to a server. Below is the ajax call that works correctly.

我有一些 javascript 代码可以将图像上传到服务器。下面是正常工作的 ajax 调用。

$.ajax({
    url: 'https://api.projectoxford.ai/vision/v1/analyses?',
    type: 'POST',
    contentType: 'application/json',
    data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }',
})

I now need to upload the image a a base64 encoding e.g.

我现在需要上传图像 aa base64 编码,例如

data: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'

But that doesn't work, i.e. the server doesn't recognise the data I send and complains.

但这不起作用,即服务器无法识别我发送的数据并抱怨。

Does anyone know what the correct format is for sending base64 encoded data in the AJAX call ?

有谁知道在 AJAX 调用中发送 base64 编码数据的正确格式是什么?

回答by carbontracking

Thanks for all the answers which helped me along.

感谢所有帮助我的答案。

I had also posted the question to the forums on https://social.msdn.microsoft.com/Forums/en-US/807ee18d-45e5-410b-a339-c8dcb3bfa25b/testing-project-oxford-ocr-how-to-use-a-local-file-in-base64-for-example?forum=mlapi(more Project Oxford specific) and between their answers and your's I've got a solution.

我还在 https://social.msdn.microsoft.com/Forums/en-US/807ee18d-45e5-410b-a339-c8dcb3bfa25b/testing-project-oxford-ocr-how-to- use-a-local-file-in-base64-for-example?forum=mlapi(更具体的牛津项目)在他们的答案和你的答案之间,我有一个解决方案。

  1. You need to send a Blob
  2. You need to set the processData:falseand contentType: 'application/octet-stream'options in the .ajax call
  1. 你需要发送一个 Blob
  2. 您需要在 .ajax 调用中设置processData:falsecontentType: 'application/octet-stream'选项

So my solution looks like this

所以我的解决方案看起来像这样

First a function to make the blob (This is copied verbatim from someone more gifted than I)

首先是一个制作 blob 的函数(这是从比我更有天赋的人那里逐字复制的)

makeblob = function (dataURL) {
            var BASE64_MARKER = ';base64,';
            if (dataURL.indexOf(BASE64_MARKER) == -1) {
                var parts = dataURL.split(',');
                var contentType = parts[0].split(':')[1];
                var raw = decodeURIComponent(parts[1]);
                return new Blob([raw], { type: contentType });
            }
            var parts = dataURL.split(BASE64_MARKER);
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;

            var uInt8Array = new Uint8Array(rawLength);

            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }

            return new Blob([uInt8Array], { type: contentType });
        }

and then

进而

$.ajax({
    url: 'https://api.projectoxford.ai/vision/v1/ocr?' + $.param(params),
    type: 'POST',
    processData: false,
    contentType: 'application/octet-stream',
    data: makeblob('data:image/jpeg;base64,9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
 })
.done(function(data) {alert("success");})
.fail(function() {alert("error");});

回答by Glenn Ferrie

This is some working code from my own application. You will need to change the contentTypeand dataargs in your ajax operations.

这是我自己的应用程序中的一些工作代码。您将需要更改ajax 操作中的contentTypedataargs。

    var video = that.vars.video;
    var code = document.createElement("canvas");

    code.getContext('2d').drawImage(video, 0, 0, code.width, code.height);

    var img = document.createElement("img");
    img.src = code.toDataURL();    

    $.ajax({
        url: '/scan/submit',
        type: 'POST',
        data: { data: code.toDataURL(), userid: userid },
        success: function (data) {
            if (data.error) {
                alert(data.error);
                return;
            }
            // do something here.
        }, 
        error : function (r, s, e) {
                alert("Unexpected error:" + e);
                console.log(r);
                console.log(s);
                console.log(e);
            } 
        });

回答by RBoschini

//After received the foto, convert to byte - C# code
Dim imagem = imagemBase64.Split(",")(1)
Dim bytes = Convert.FromBase64String(imagem)

You load the image in canvas, not necessary upload to server.

您在画布中加载图像,无需上传到服务器。

var ctx = canvas.getContext('2d');
ctx.drawImage(img, selection.x, selection.y, selection.w, selection.h, 0, 0, canvas.width, canvas.height);

var ctxPreview = avatarCanvas.getContext('2d');
ctxPreview.clearRect(0, 0, ctxPreview.width, ctxPreview.height);


ctxPreview.drawImage(img, selection.x, selection.y, selection.w, selection.h, 0, 0, canvas.width, canvas.height);

$('#avatarCanvas').attr('src', canvas.toDataURL());
$('#hdImagembase64').val(canvas.toDataURL());

See, this code get image and draw in canvas, after draw you get base64 string with canvas.toDataURL()

看,此代码获取图像并在画布中绘制,绘制后使用 canvas.toDataURL() 获取 base64 字符串

try this :D

试试这个:D

回答by Andy W

The data parameter for jQuery's $.ajax call can be a String, Object, or Array. Based on the working example you gave, it looks like your upload script expects a parameter called "Url":

jQuery 的 $.ajax 调用的数据参数可以是字符串、对象或数组。根据您提供的工作示例,您的上传脚本似乎需要一个名为“Url”的参数:

data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }'

If you wanted to pass the parameter as an Object, you might try:

如果您想将参数作为对象传递,您可以尝试:

data: {
  Url: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
}

If you want to pass it as a String, you might try:

如果您想将其作为字符串传递,您可以尝试:

data: '{ "Url": "data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z"}'