我正在尝试将图像数据发送到服务器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's 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
。以前有人遇到过这个问题吗?你是怎么解决的?
答案 0 :(得分:-1)
您可以尝试将磁盘中的映像作为ReadStream加载,并使用request module将其加载到API。
粗略的例子:
composer dump-autoload
该模块可通过fs.createReadStream(filename).pipe(request.put('http://example.com/api/images'))
获得。