【问题标题】:Post form with file using Node.js使用 Node.js 发布带有文件的表单
【发布时间】:2017-11-08 15:09:36
【问题描述】:

有一个用于创建文章的外部(我无法更改)API。使用此 API,我成功地以这种方式创建了一篇文章:

curl -F "article[id]=607822" -F "article[file]=@/article_file_example/article" 'https://api/v2/articles'

如何使用 Node.js(最好使用 axios)执行以下 http 请求?

代码应该适用于 Linux 和 Windows,所以我不能使用 require('child_process').exec

我尝试了以下方法:

    const formData = {
        'id': 607822,
        file: fs.createReadStream(filePath), //filePath is the absolute path to the file
    };

    axios.post('https://api/v2/articles', {article: formData});

但是API响应是验证错误,也就是说我没有成功模仿curl命令。

有什么建议吗?

附:一旦我有一个可行的解决方案,我还想执行一项改进。我有文件内容,所以我更喜欢直接发送而不创建文件+ createReadStream。我试图这样做 Blobing context,但没有成功。

【问题讨论】:

    标签: node.js forms curl file-upload


    【解决方案1】:

    看起来 axios 不支持发送 multipart/form-data:https://github.com/mzabriskie/axios/issues/789

    我的解决方案基于以下答案之一: Nodejs POST request multipart/form-data

    我使用了restler 模块。

    我无法发送我的数据:

    {
        article: {
            'id': 607822,
            file: restler.file(filePath, null, stats.size, null, "text/plain")
        }
    }
    

    因为它没有被服务器正确检索。

    所以我不得不将其转换为:

    {
        'article[id]': 607822,
        'article[file]': restler.file(filePath, null, stats.size, null, "text/plain")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      相关资源
      最近更新 更多