2016-04-15 92 views
-1

我想通过使用POST方法如何在node.js中使用POST方法传输文件?

var queryString = querystring.stringify({ 
    "category": "1", 
    "photo": "/home/dmitriy/image2.jpg" // HOW I CAN TO TRANSFER THIS IMAGE? 
}); 

var options = { 
    hostname: 'dimonchikone.ucoz.net', 
    port: 80, 
    path: '/uapi/photo', 
    method: method, 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Content-Length': queryString.length 
    } 
}; 

var req = http.request(options, function(res) { 
    console.log('STATUS: ' + res.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res.headers)); 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     console.log('BODY: ' + chunk); 
    }); 
}); 

req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

// write data to request body 
req.write(queryString); 
req.end(); 

将图像传送,但不知道如何?在php中,当我使用curl我只写下代码

"photo": "@/home/dmitriy/image2.jpg" 

如何我可以在node.js中传输此文件?我想传递的图像,然后获得使用PHP $ _FILE

回答

1

我建议使用requestmodule,它变得微不足道:

fs.createReadStream('/home/dmitriy/image2.jpg').pipe(request.put('http://dimonchikone.ucoz.net/uapi/photo/image2.jpg'))