使用原始HTML当我发布一个文件到flask服务器使用以下我可以从flask请求全局访问文件:

<form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
    <input type="file" id="file" name="file">
    <input type=submit value=Upload>
</form>

瓶:

def post(self):
    if 'file' in request.files:
        ....

当我尝试用Axios做同样的事情时,flask请求全局是空的:

<form id="uploadForm" enctype="multipart/form-data" v-on:change="uploadFile">
<input type="file" id="file" name="file">
</form>

uploadFile: function (event) {
    const file = event.target.files[0]
    axios.post('upload_file', file, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
    })
}

如果我使用上面相同的uploadFile函数,但从axios中删除headers json。post方法我在我的flask请求对象的表单键中获得字符串值的csv列表(文件是.csv)。

如何通过axios获取文件对象?


当前回答

这是我的方式:

var formData = new FormData(formElement);
// formData.append("image", imgFile.files[0]);
const res = await axios.post(
  "link-handle",
  formData,
  {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }
);

其他回答

将文件添加到一个formData对象中,并将Content-Type头设置为multipart/form-data。

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

使用Vue的示例应用程序。需要一个运行在本地主机上的后端服务器来处理请求:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE

这对我有用,我希望能对别人有所帮助。

var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
    .then(res => {
        console.log({res});
    }).catch(err => {
        console.error({err});
    });

如何在内存中使用对象发布文件(如JSON对象):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

这是我的方式:

var formData = new FormData(formElement);
// formData.append("image", imgFile.files[0]);
const res = await axios.post(
  "link-handle",
  formData,
  {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }
);