如何通过Axios将文件发送到Laravel

Ham*_*ava 7 php laravel vue.js axios vuejs2

我需要通过Axios将文件从客户端发布到服务器.

这是我的Vuejs代码:

methods: {
    'successUpload': function (file) {
        const config = { headers: { 'Content-Type': 'multipart/form-data' } };
        axios.post('/Upload/File',file, config).then(function (response) {
            console.log(response.data);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我用于处理已发送文件的Laravel代码:

public function uploadFile(Request $request)
{
    if($request->hasFile('file'))
      return "It's a File";

    return "No! It's not a File";
}
Run Code Online (Sandbox Code Playgroud)

但它总是回归No It's not a File.

任何帮助将非常感激.

who*_*boy 14

您必须创建一个FormData对象并附加图像文件.

methods: {
  'successUpload': function (file) {

    let data = new FormData();
    data.append('file', document.getElementById('file').files[0]);

    axios.post('/Upload/File',data).then(function (response) {
        console.log(response.data);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

一个例子是在这里.

如果有效,请告诉我.