如何通过Axios将文件发送到Laravel [英] How to send a file via Axios to Laravel

查看:91
本文介绍了如何通过Axios将文件发送到Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的Vuejs代码:

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

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

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

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

任何帮助将不胜感激.

推荐答案

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

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

例如此处.

让我知道是否可行.

这篇关于如何通过Axios将文件发送到Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆