【发布时间】:2019-10-09 22:09:06
【问题描述】:
我正在尝试在我的计算机上选择一个图像并使用文件元素将数据传递到 REST 端点。
<input type="file" id="input">
我能够渲染图像并将其显示在浏览器中。但是,在将图像传递到端点时,我得到一个空字符串或对象,如下面的代码所示。
(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));
}})();
服务如下所示:
[OperationContract]
[WebInvoke(UriTemplate = "/AddPhoto/", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat =
WebMessageFormat.Json)]
void AddPhoto(BlogEntityModel blogEntityModel);
【问题讨论】:
标签: javascript c# wcf