【问题标题】:How to post an image in base64 encoding via .ajax?如何通过 .ajax 以 base64 编码发布图像?
【发布时间】:2015-12-02 16:18:57
【问题描述】:

我有一些将图像上传到服务器的 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" }',
})

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

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

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

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

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

感谢所有帮助我的答案。

我也在论坛上发布了这个问题 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. 你需要发送一个 Blob
  2. 您需要在.ajax 调用中设置processData:falsecontentType: 'application/octet-stream' 选项

所以我的解决方案是这样的

首先是一个制作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 });
        }

然后

$.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");});

【讨论】:

  • 这很好用,makeBlob 将数据转换为可以传递给情感 API 的格式。伟大的!这应该被标记为答案?
  • 过去两天我一直在努力将本地文件数据发送到人脸检测 api,这就像一个魅力。谢谢
  • 另外,更改 contentType: 'image/png' 对我来说效果很好。唯一的好处是目标服务器将其识别为图像,我仍然必须添加 .PNG 扩展名才能打开文件
【解决方案2】:

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

    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);
            } 
        });

【讨论】:

    【解决方案3】:
    //After received the foto, convert to byte - C# code
    Dim imagem = imagemBase64.Split(",")(1)
    Dim bytes = Convert.FromBase64String(imagem)
    

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

    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());
    

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

    试试这个:D

    【讨论】:

      【解决方案4】:

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

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

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2017-11-19
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 2013-11-10
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        相关资源
        最近更新 更多