[英]Send image data to an API nodejs
我正在尝试将图像数据发送到服务器API,但该API随附的文档仅包含JQuery的示例,我不希望将其与我的nodejs项目一起使用。 另外,JQuery示例包含Node中不存在的内容,例如Blob。
API提供的示例是:
var sourceImage = new Image();
sourceImage.src = image; // add image data to object
sourceImage.onload = function() {
// Create a canvas with the desired dimensions
var canvas = document.createElement("canvas");
var dim = 256; // the image size
canvas.width = dim;
canvas.height = dim;
// Scale and draw the source image to the canvas
canvas.getContext("2d").drawImage(sourceImage, 0, 0, dim, dim);
var formDataWithCanvasImage = createFormData(canvas);
// Make ajax call here
}
function createFormData(canvas) {
var b64Img = canvas.toDataURL();
var binImg = dataURItoBlob(b64Img);
var fileName = new Date().getTime();// Name the file with the current timestamp and no extension
var fd = new FormData();
fd.append("imageClass", "preview");
fd.append("X-Requested-With", "Iframe");
fd.append("X-HTTP-Accept", "application/json, text/javascript, */*; q=0.01");
fd.append("file", binImg,fileName);
return fd;
}
$.ajax({
url: imageURL,
data: formDataWithCanvasImage,
processData: false,
contentType: false,
type: 'POST',
error: function() {alert("error uploading image");},
success: function(data){
console.log(data);
}
});
但是,这不适用于nodejs,因为nodejs中没有画布,也没有blob之类的东西。 因此,我要做的是从本地磁盘读取图像,并将该缓冲区转换为ArrayBuffer,然后将其编码为Analog-nico的request-promise,如下所示:
let opts = {
uri: 'https://*****.com/api/images',
contentType: false,
processData: false,
type: 'POST',
formData: {
"imageClass": "application",
"X-Requested-With": "Iframe",
"X-HTTP-Accept": "application/json, text/javascript, */*; q=0.01"
"file": arraybuffer
},
}
request.post(opts).then(data => {....});
但是代码抛出TypeError: source.on is not a function
。 有人遇到过这个问题吗? 您是如何解决的?
您可以尝试从磁盘作为ReadStream加载映像,然后使用请求模块将其传递到API。
粗略示例: fs.createReadStream(filename).pipe(request.put('http://example.com/api/images'))
该模块可通过npm install request
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.