如何使用 JavaScript 上传嵌入的图像?

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

How can I upload an embedded image with JavaScript?

javascriptimageupload

提问by andyknas

I'd like to build a simple HTML page that includes JavaScript to perform a form POST with image data that is embedded in the HTML vs a file off disk.

我想构建一个简单的 HTML 页面,其中包含 JavaScript 以使用嵌入在 HTML 中的图像数据与磁盘外的文件执行表单 POST。

I've looked at this post which would work with regular form data but I'm stumped on the image data.

我看过这篇文章,它可以处理常规表单数据,但我对图像数据感到困惑。

JavaScript post request like a form submit

JavaScript post 请求就像表单提交一样

回答by Joe Coder

** UPDATE ** Feb. 2014 **

** 更新 ** 2014 年 2 月 **

New and improved version available as a jQuery plugin: https://github.com/CoeJoder/jquery.image.blob

新的和改进的版本可用作 jQuery 插件:https: //github.com/CoeJoder/jquery.image.blob

Usage:

用法:

$('img').imageBlob().ajax('/upload', {
    complete: function(jqXHR, textStatus) { console.log(textStatus); } 
});





Requirements

要求

Thus the browser requirements are:

因此浏览器的要求是:

  • Chrome: 20+
  • Firefox: 13+
  • Internet Explorer: 10+
  • Opera: 12.5+
  • Safari: 6+
  • 铬:20+
  • 火狐:13+
  • Internet Explorer:10+
  • 歌剧:12.5+
  • 野生动物园:6+

Note: The images must be of the same-originas your JavaScript, or else the browser security policy will prevent calls to canvas.toDataURL()(for more details, see this SO question: Why does canvas.toDataURL() throw a security exception?). A proxy server can be used to circumvent this limitation via response header injection, as described in the answers to that post.

注意:图像必须与您的 JavaScript同源,否则浏览器安全策略将阻止调用canvas.toDataURL()(有关更多详细信息,请参阅此 SO 问题:为什么 canvas.toDataURL() 会抛出安全异常?)。代理服务器可用于通过响应标头注入来规避此限制,如该帖子的答案中所述。

Here is a jsfiddleof the below code. It should throw an error message, because it's not submitting to a real URL ('/some/url'). Use firebug or a similar tool to inspect the request data and verify that the image is serialized as form data (click "Run" after the page loads):

这是以下代码的jsfiddle。它应该抛出一条错误消息,因为它没有提交到真实的 URL ('/some/url')。使用 firebug 或类似工具检查请求数据并验证图像是否已序列化为表单数据(页面加载后单击“运行”):

POST data

发布数据

Example Markup

示例标记

<img id="someImage" src="../img/logo.png"/>

The JavaScript

JavaScript

(function() {
    // access the raw image data
    var img = document.getElementById('someImage');
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
    var dataUrl = canvas.toDataURL('image/png');
    var blob = dataUriToBlob(dataUrl);

    // submit as a multipart form, along with any other data
    var form = new FormData();
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/some/url', true);    // plug-in desired URL
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                alert('Success: ' + xhr.responseText);
            } else {
                alert('Error submitting image: ' + xhr.status);
            }
        }
    };
    form.append('param1', 'value1');
    form.append('param2', 'value2');
    form.append('theFile', blob);
    xhr.send(form);

    function dataUriToBlob(dataURI) {
        // serialize the base64/URLEncoded data
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0) {
            byteString = atob(dataURI.split(',')[1]);
        }
        else {
            byteString = unescape(dataURI.split(',')[1]);
        }

        // parse the mime type
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

        // construct a Blob of the image data
        var array = [];
        for(var i = 0; i < byteString.length; i++) {
            array.push(byteString.charCodeAt(i));
        }
        return new Blob(
            [new Uint8Array(array)],
            {type: mimeString}
        );
    }
})();

References

参考

SO: 'Convert DataURI to File and append to FormData

SO: '将 DataURI 转换为文件并附加到 FormData

回答by prashanth

Assuming that you are talking about embedded image data like http://en.wikipedia.org/wiki/Data_URI_scheme#HTML

假设您正在谈论嵌入式图像数据,如http://en.wikipedia.org/wiki/Data_URI_scheme#HTML

****If my assumption is incorrect, please ignore this answer.**

****如果我的假设不正确,请忽略此答案。**

You can send it as JSON using XMLHttpRequest. Here is sample code: (you may want to remove the header part ('data:image/png;base64,') before sending)

您可以使用 XMLHttpRequest 将其作为 JSON 发送。这是示例代码:(您可能希望在发送之前删除标题部分 ('data:image/png;base64,'))

Image

图片

<img id="myimg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

Button

按钮

<input id="subbtn" type="button" value="sub" onclick="sendImg()"></input>

Script

脚本

function sendImg() {
    var dt = document.getElementById("myimg").src;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/Home/Index', true); //put your URL instead of '/Home/Index'
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) { //4 means request finished and response is ready
            alert(xhr.responseText);
        }
    };
    var contentType = "application/json";
    xhr.setRequestHeader("Content-Type", contentType);

    for (var header in this.headers) {
        xhr.setRequestHeader(header, headers[header]);
    }

    // here's our data variable that we talked about earlier
    var data = JSON.stringify({ src: dt });

    // finally send the request as binary data
    xhr.send(data);
}

EDIT

编辑

As @JoeCoder suggests, instead of json, you can also use a FormData object and send in Binary format. Check his answerfor more details.

正如@JoeCoder 所建议的,除了 json,您还可以使用 FormData 对象并以二进制格式发送。查看他的回答以获取更多详细信息。