2016-08-12 62 views
0

我试图图像数据发送到服务器API,不过,附带的文档API只包含JQuery的,我不希望我的项目的NodeJS使用的例子。此外,JQuery示例还包含Node中不存在的内容,例如Blob。发送图像数据的API的NodeJS

由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帆布,并没有这样的事,作为一个斑点。所以,我所做的就是读取本地磁盘的图像和缓冲区转换成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

斑点是JavaScript的一部分.... http://www.javascripture.com/Blob – Hackerman

+0

不中的NodeJS部分。 https://stackoverflow.com/questions/14653349/node-js-can%C2%B4t-create-blobs –

+0

我认为你错过了点...你可以将Jquery移植到JavaScript并使用普通的JS ...在客户端上构建请求并将其发送到服务器在几乎所有与Web相关的编程语言中都是一项简单的任务:) – Hackerman

回答

-1

你可以试试使用request module的API从磁盘加载图像作为ReadStream和管道。

粗糙实施例: fs.createReadStream(filename).pipe(request.put('http://example.com/api/images'))

该模块经由npm install request可用。

+0

未正确写入服务器,但未返回错误。 –