简体   繁体   中英

Problem with uploading file through form-data axios

I am trying to upload on server file, but it gives me the response that file isn't selected. Doing the same thing as in documentation of axios and form-data, but still have errors.

let form = new FormData();
form.append('file', fs.createReadStream('./files/50.jpg'));

const config = {
    headers: {
        ...form.getHeaders(),
        Authorization: token
    }
}

axios.post(url, form, config)
.then(response => console.log(response.data, response.status))
.catch(err => console.error(err.config, err.response.data))

And the response is

{
  url: 'https://example.com',
  method: 'post',
  data: FormData {
    _overheadLength: 148,
    _valueLength: 0,
    _valuesToMeasure: [ [ReadStream] ],
    writable: false,
    readable: true,
    dataSize: 0,
    maxDataSize: 2097152,
    pauseStreams: true,
    _released: true,
    _streams: [],
    _currentStream: null,
    _insideLoop: false,
    _pendingNext: false,
    _boundary: '--------------------------897634953482711246524185',
    _events: [Object: null prototype] { error: [Function: handleStreamError] },
    _eventsCount: 1
  },
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'multipart/form-data; boundary=--------------------------897634953482711246524185',
    Authorization: 'Bearer token',
    'User-Agent': 'axios/0.19.2'
  },
  transformRequest: [ [Function: transformRequest] ],
  transformResponse: [ [Function: transformResponse] ],
  timeout: 0,
  adapter: [Function: httpAdapter],
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
  maxContentLength: -1,
  validateStatus: [Function: validateStatus]
} { errors: [ { code: 65536, message: 'Must upload one file' } ] }

Help me please how to upload file, where is the error? Or maybe u can give some alternative ways to solve this case.

here my code to upload file in node.js, it works ok.

    const form = new FormData();
    const file = fse.createReadStream(option.filePath);
    form.append('file', file);
    const header: any = form.getHeaders();
    const reqData = axios({
      method: 'post',
      url: 'myURL',
      data: form,
      headers: header,
      httpsAgent: new https.Agent({
        rejectUnauthorized: false
      }),
      maxContentLength: Infinity,
      maxBodyLength: Infinity,
      onUploadProgress: (progressEvent: any) => {
        const complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%';
        console.log('upload percent: ' + complete);
      }
    }).then((response: any) => {});

Thanks for everyone, but i found the answer in Postman.Code -> NodeJs - Axios

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('file', fs.createReadStream('/Users/anton/Downloads/50 (1).jpg'));

var config = {
  method: 'post',
  url: 'https://...',
  headers: { 
    'Authorization': 'Bearer ...', 
    'Content-Type': 'multipart/form-data', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM