None
None

Reputation: 9247

How to handle image file in vue.js?

In my view i have this:

  <input type="file" @change="onFileChange">

In vue i have this:

 onFileChange:function(e) {
              var files = e.target.files || e.dataTransfer.files;
              if (!files.length)
                return;
              this.createImage(files[0]);
              this.intro_image  = files[0];

            },
            createImage:function(file) {
              var image = new Image();
              var reader = new FileReader();
              var vm = this;

              reader.onload = (e) => {
                vm.image = e.target.result;
              };
              reader.readAsDataURL(file);

            },

  editProperty: function() {
                user_id = this.user_credentials.user_id;
                property_id = this.property_credentials.property_id;


                var property_credentials = {

                    intro_image: this.intro_image

                };

                this.$http.patch('/profile/'+ user_id +'/property/'+ property_id +'/edit', property_credentials).then(function(response) {
                    $("html, body").animate({ scrollTop: 0 }, "slow");
                    this.property_status = true;
                    this.property_success_update_message = response.data.successUpdateMsg;
                } , function(response) {
                    $("html, body").animate({ scrollTop: 0 }, "slow");
                    this.property_status = false;
                    this.property_errors = response.data
                });
            },

In my controller im trying this but always get null:

  $intro_image = $request->intro_image;

Any suggestion how can i get file from vue in my controller so that i can use this bellow:

  if(!empty($intro_image)) {
            $uploads_path_image = public_path() . '/storage/uploads/';
            $property_default_image_folder = 'property' . $property->id;
            $orginalImageName = $intro_image->getClientOriginalName();
            $imageName = rand(1, 10000) . '.' . $intro_image->getClientOriginalExtension();
            $property_image_path = $property_default_image_folder . '/' . $imageName;
            if (!File::isDirectory($uploads_path_image . $property_default_image_folder)) {
                File::makeDirectory($uploads_path_image . $property_default_image_folder, 0775, true, true);
            }
            $intro_image->move(base_path() . '/public/storage/uploads/' . $property_default_image_folder, $imageName);

            $property->default_image = $imageName;
          }

Upvotes: 0

Views: 686

Answers (1)

krisanalfa
krisanalfa

Reputation: 6438

Try this:

var formData = new FormData();

formData.append('intro_image', this.intro_image);

this.$http.patch('/profile/'+ user_id +'/property/'+ property_id +'/edit', formData)

Upvotes: 1

Related Questions