使用原始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获取文件对象?


当前回答

如何在内存中使用对象发布文件(如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);
}

其他回答

如果你不想使用FormData对象(例如,你的API接受特定的内容类型签名,multipart/ FormData不是其中之一),那么你可以这样做:

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

如何在内存中使用对象发布文件(如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",
    },
  }
);

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

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

对我来说,错误是我控制器中的实际参数名称……我花了好长时间才想明白,也许能帮到别人。我使用Next.js / .Net 6

客户:

export const test = async (event: any) => {
    const token = useAuthStore.getState().token;
    console.log(event + 'the event')
    if (token) {
        const formData = new FormData();
        formData.append("img", event);
        const res = await axios.post(baseUrl + '/products/uploadproductimage', formData, {
            headers: {
                'Authorization': `bearer ${token}`
            }
        })
        return res
    }
    return null
}

服务器:

 [HttpPost("uploadproductimage")]
        public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
        {
            return Ok();
        }

错误,因为服务器期望参数“image”而不是“img”:

formData.append("img", event);

 public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)