How to send a file via Axios to Laravel

风流意气都作罢 提交于 2019-12-01 02:29:07

问题


I need to post a File from client to server via Axios.

Here is my Vuejs code :

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);
        });
    }
}

And here is my Laravel code for handling sent file :

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

    return "No! It's not a File";
}

But it always returns No It's not a File.

Any helps would be great appreciated.


回答1:


You have to create a FormData object and append the image file.

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);
    });
  }
}

An example is here.

Let me know if that works.



来源:https://stackoverflow.com/questions/42907747/how-to-send-a-file-via-axios-to-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!