Ajax使用Axios从文件系统发布文件

时间:2019-03-20 16:20:49

标签: node.js axios

我正在寻找一种方法,如何使用nodejs axios客户端将文件从本地文件系统发送到服务器。

1 个答案:

答案 0 :(得分:0)

https://gist.github.com/binki/10ac3e91851b524546f8279733cdadad

#!/usr/bin/env node
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const filePath = __dirname + '/../accept-http-post-file/cookie.jpg';
fs.readFile(filePath, (err, imageData) => {
  if (err) {
    throw err;
  }
  const form = new FormData();
  form.append('file', imageData, {
    filepath: filePath,
    contentType: 'image/jpeg',
  });
  axios.post('http://localhost:3000/endpoint', form, {
    headers: form.getHeaders(),
  }).then(response => {
    console.log('success! ', response.status, response.statusText, response.headers, typeof response.data, Object.prototype.toString.apply(response.data));
  }).catch(err => {
    console.log(err);
  });
});