Reputation: 71
I dragged an image to my browser.Now I have the data URL.How can I upload it to the server with jQuery method?
Upvotes: 3
Views: 8494
Reputation: 589
You need a server side code to get the image and store it. It doesn't happen magically. You can search the stackoverflow for how to transfer data from client to server using ajax / XmlHttpRequest
I have following example which transfer an image from page to a server. Please note that the image is already visible in the page. This may not be the best options but works for me. You can utilize this code to get your image to data stream and use the ajax call here.
Here is the html code
<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>
Here is the javascript to transfer image data to the server
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;
}
}
});
}
}
On the server I have a webservice running and the following function captures the image data and saves it. You need to set server side rights to read/write on disk (keep in your mind).
[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;
}
You may need to some work to publish your web service to your local IIS.
Upvotes: 1