使用Vue和Laravel上传文件 [英] File upload with Vue and Laravel

查看:149
本文介绍了使用Vue和Laravel上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用vue和laravel进行一个简单的User Avatar更新,但我无法弄清楚我在做什么错.

I'm trying to make a simple User Avatar update using vue and laravel and I can't figure what I'm doing wrong here.

我有一个具有这种形式和脚本的vue组件:

I have a vue component with this form and this script:

<form @submit.prevent="updateAvatar" action="#" method="POST" enctype="multipart/form-data">
        <div class="form-group">
          <label name="task-title">Incarca poza:</label>
          <input @change="newAvatar" id="avatar" type="file" name="avatar">
        </div>
        <button type="submit" class="btn btn-primary general-task-btn">Actualizeaza</button>
      </form>

<script>
export default{
    props: ['userid'],
    data(){
        return{
            avatar: {
            }
        }
    },
    methods: {
    newAvatar(event) {
       let files = event.target.files;
       if (files.length) this.avatar = files[0];
    },
    updateAvatar: function () {
        let data = new FormData();
        data.append('file', this.avatar);
        axios.put('/api/user/updateAvatar', data)
                .then(res => {
                    console.log(res);
                 }) 
                 .catch(error => console.log(error));
        // window.location.href = "/profile";
      }
    }
}

控制器功能:

    public function updateAvatar(Request $request)
{
    $user = Auth::user();
    $avatar = $request->file('file');
    $filename = time() . '.' . $avatar->getClientOriginalExtension();
    Image::make($avatar)->save( public_path('/uploads/avatars' . $filename) );

    $user->avatar = $filename;

    $user->save();
}

我真正不知道的是如何访问通过axios发送的formData.服务器告诉我那是空的. 我在发出放置请求之前尝试console.log formData,但是即使内容在头像对象中,我也会得到一个空的obj.当我在线阅读时,您看不到formData的内容,因此我无法确定数据是否正确发送. 也许你们可以让我明白这一点.

What I really don't know is how to access that formData that I sent with axios. The server tells me that is empty. I tried to console.log the formData before making the put request but I get an empty obj even if the content is in the avatar object. As I read online, you can't see the content of a formData so I can't figure if the data is being sent correctly or not. Maybe you guys can make this clear for me.

推荐答案

这似乎与此问题有关 https://github.com/laravel/framework/issues/13457

That seems to be related to this issue https://github.com/laravel/framework/issues/13457

尝试更换

let data = new FormData(); 
data.append('file', this.avatar);
data.append('_method', 'put'); // add this
axios.post('/api/user/updateAvatar',data) // change this to post )
.then(res =>{
   console.log(res); 
}) 
.catch(error => console.log(error)); //             
   window.location.href = "/profile";
}

这篇关于使用Vue和Laravel上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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