Reputation: 45
I am attempting to select an image on my computer and pass the data to a REST endpoint using the file element.
<input type="file" id="input">
I am able to render the image and display it in the browser. However, I get an empty string or object when passing the image to the endpoint as shown in the code below.
(function () {
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const reader = new FileReader();
reader.onload = (function() {
return function(e) {
sendFile(e.target.result);
};
})();
reader.readAsDataURL(this.files[0]);
}
function sendFile(file) {
let img = {
'Photo': new Blob([file], {type : 'image/png'})
};
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
};
xhr.open('POST', 'http://localhost/example/service.svc/AddPhoto/', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify(img));
}})();
Service looks like this:
[OperationContract]
[WebInvoke(UriTemplate = "/AddPhoto/", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat =
WebMessageFormat.Json)]
void AddPhoto(BlogEntityModel blogEntityModel);
Upvotes: 1
Views: 267
Reputation: 5769
If you want to send the file as JSON, you have to take into account two things:
e.target.result
is a data URI.stringify
method.So, to fix it, you just should replace 'Photo': new Blob([file], {type : 'image/png'})
with 'Photo': file
.
Keep in mind that in your case, the variable file
is a data URI. If you want to submit only the Base64 value you have to remove the data:image/xxx;base64,
prefix.
Upvotes: 2