Javascript 如何使用jQuery方法从数据URL上传图像?

Javascript 如何使用jQuery方法从数据URL上传图像?,javascript,html,image-uploading,jquery-file-upload,Javascript,Html,Image Uploading,Jquery File Upload,我将图像拖到浏览器中。现在我有了数据URL。如何使用jQuery方法将其上载到服务器?您需要服务器端代码来获取图像并存储它。这不是神奇的。您可以在stackoverflow中搜索如何使用ajax/XmlHttpRequest将数据从客户端传输到服务器 我有下面的例子,它将图像从页面传输到服务器。请注意,图像已在页面中可见。这可能不是最好的选择,但对我来说很有效。您可以利用此代码将图像转换为数据流,并在此处使用ajax调用 下面是html代码 <input id="filenametext"

我将图像拖到浏览器中。现在我有了数据URL。如何使用jQuery方法将其上载到服务器?

您需要服务器端代码来获取图像并存储它。这不是神奇的。您可以在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>
在服务器上,我运行了一个webservice,下面的函数捕获图像数据并保存它。您需要设置服务器端对磁盘的读/写权限(请记住)


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

这取决于服务器,不是吗?
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;
                    }
                }
            });
        }
    }
    [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;
    }