2017-06-14 52 views
0

如何上传一个字符串作为文件,并通过http post请求使用node.js上传一个字符串作为文件

这里是我的尝试:

var unirest = require('unirest'); 
    unirest.post('127.0.0.1/upload') 
    .headers({'Content-Type': 'multipart/form-data'}) 
    .attach('file', 'test.txt', 'some text in file') // Attachment 
    .end(function (response) { 
     console.log(response.body); 
    }); 

但没有任何反应

回答

0

您必须指定从本地文件系统中的文件。所以,我劝

  1. create the file locally

    var fs = require('fs'); 
    fs.writeFile("/tmp/test", "some text in file", function(err) { 
        if(err) { return console.log(err); } 
        console.log("The file was saved!"); 
    }); 
    
  2. 发送文件

    var unirest = require('unirest'); 
    unirest.post('127.0.0.1/upload') 
        .headers({'Content-Type': 'multipart/form-data'}) 
        .attach('file', '/tmp/test') 
        .end(function (response) { 
         console.log(response.body); 
        }); 
    
相关问题