【问题标题】:How can I upload an image from Data URL with jQuery method?如何使用 jQuery 方法从数据 URL 上传图像?
【发布时间】:2015-08-26 22:30:14
【问题描述】:

我把一张图片拖到了浏览器,现在我有了数据的URL,我怎么用jQuery方法把它上传到服务器?

【问题讨论】:

  • 这取决于服务器,不是吗?

标签: javascript html image-uploading jquery-file-upload


【解决方案1】:

您需要一个服务器端代码来获取图像并存储它。它不会神奇地发生。您可以在 stackoverflow 中搜索如何使用 ajax / XmlHttpRequest 将数据从客户端传输到服务器

我有以下示例将图像从页面传输到服务器。请注意,该图像已在页面中可见。这可能不是最好的选择,但对我有用。您可以利用此代码将图像传输到数据流并在此处使用 ajax 调用。

这里是html代码

<input id="filenametext" maxlength="50" />
<div id="divimage" style="border:2px solid red;margin-bottom:10px;margin-top:10px;">
    <canvas id="myimage" width="400" height="200" style="border:2px solid orange; margin:5px 5px 5px 5px;"></canvas>
</div>

这是将图像数据传输到服务器的 javascript

function btnSaveImage() {
        var imgdata;
        var imgdata2;
        var image = document.getElementById("myimage");
        if (image != null) {
            imgdata2 = image.toDataURL("image/png");
            imgdata = imgdata2.replace('data:image/png;base64,', '');
        }

        var txt = $('#filenametext').val();

        if (imgdata != null) {
            $.ajax({
                type: 'POST',
                url: 'http://localhost/MyWebService/WebServicePage.asmx/SaveImage',
                data: '{"fname":"' + txt + '","image":"' + imgdata + '"}',
                contentType: 'application/json; charset=utf-8',
                success: function (msg) {
                    $('#status').val('');
                    $('#statustext').val(msg);
                },
                error: function(xhr, status, msg) {
                    $('#status').val(status);
                    $('#statustext').val(msg);

                    var txtres = document.getElementById("response_div");
                    if (txtres != null) {
                        txtres.innerText = xhr.responseText;
                    }
                }
            });
        }
    }

在服务器上,我运行了一个 web 服务,以下函数捕获图像数据并保存它。您需要设置服务器端权限以在磁盘上读取/写入(请记住)。

    [WebMethod]
    public int SaveImage(string fname, string image) {
        string filename = HttpContext.Current.Server.MapPath("~/images/") + fname;
        using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create)) {
            byte[] data = Convert.FromBase64String(image);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
            bw.Write(data);
            bw.Close();
        }

        return 0;
    }

您可能需要做一些工作才能将 Web 服务发布到本地 IIS。

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 2022-01-22
    • 2018-08-20
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多