如何将 Base64 编码图像传递到 WCF REST 端点
How to pass Base64 encoded image to WCF REST endpoint
我正在尝试 select 我计算机上的图像并使用文件元素将数据传递到 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);
如果您想将文件作为 JSON 发送,您必须考虑两件事:
e.target.result
的值是一个数据 URI。
- 您不能使用
stringify
方法将 Blob 转换为 JSON。
因此,要修复它,您只需将 'Photo': new Blob([file], {type : 'image/png'})
替换为 'Photo': file
。
请记住,在您的例子中,变量 file
是一个数据 URI。如果您只想提交 Base64 值,则必须删除 data:image/xxx;base64,
前缀。
我正在尝试 select 我计算机上的图像并使用文件元素将数据传递到 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);
如果您想将文件作为 JSON 发送,您必须考虑两件事:
e.target.result
的值是一个数据 URI。- 您不能使用
stringify
方法将 Blob 转换为 JSON。
因此,要修复它,您只需将 'Photo': new Blob([file], {type : 'image/png'})
替换为 'Photo': file
。
请记住,在您的例子中,变量 file
是一个数据 URI。如果您只想提交 Base64 值,则必须删除 data:image/xxx;base64,
前缀。