使用Vuejs上传文件

雅西

我在Laravel工作。我需要使用Vuejs上传文件。但它不起作用。我添加以下代码:

刀片(文件上传):

<input class="form-control" type="file" >

脚本视图:var app = new Vue({el:'#app',

data: {
person: {
        id: 0,
        user_name:'',
        position_id:'',
        image:'',
        },
        },


    methods: {
      addPerson: function () {
        axios.post('/addperson', this.person)
            .then(response => {
                console.log(response.data);
                if (response.data.etat) {
                    this.person = {
                         id: 0,
                          user_name: response.data.etat.user_name,
                          position_name: response.data.etat.position_id,
                          image: response.data.etat.image
                    };
                }

            })
            .catch(error => {
                console.log('errors: ', error)
            })
    },

控制器:

public function addPerson(Request $request){
$person = new Person;

$person->user_name=$request->user_name;
$person->position_id=$request->position_id;
 if($request->hasFile('photo')){
     $person->image= $request->image->store('image');
    }
$person->save();

return back()->with('success', 'New Position added successfully.');

我的Axios发布功能在没有图像上传行代码的情况下可以正常工作。我只是不知道如何添加上传代码。

谢谢有人的帮助。

北极星

在您的刀片文件中

<input type="file" @change="onFileChange" name="id_image" id="id_image" class="inputFile">

在您的vue.js文件中的方法下:

    onFileChange(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createImage(files[0]);
            },

createImage(file) {
            let reader = new FileReader();
            reader.onload = (e) => {
                this.person.image = e.target.result;
            };
            reader.readAsDataURL(file);
        },

那应该允许您的axios代码上传图像。请注意,它是在base64中上传的,因此,如果您需要验证器,则必须为base64图像创建自定义验证器。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章