simseag's avatar

Problem uploading files with Vue.js

Hi,

I'm trying to upload images using a form I made in Vue.js. I've tried to figure this out for a while but it's driving me nuts. The request has the image in it, but when I try and get it from the request object in my controller, it tells me the image is null!

Here's the relevant part my Vue.js template:

Here's my uploading code: update: function(event) {

$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

var ajaxPath = location.origin + '/assets/image/'; var ajaxMethod = 'PATCH';

var imgData = new FormData($("#img-upload-"+this.image.id)[0]);

imgData.append('image_data', JSON.stringify(this.image));

$.ajax( { url: ajaxPath, method: ajaxMethod, //contentType: false, processData: false, //mimeType:"multipart/form-data", data: imgData }) .done(function(data) { console.log("Success!"); this.image = data; this.edit = false; }.bind(this)) .fail(function(data) { console.log("Fail!"); });

}

Here's the Form Data that was sent: ------WebKitFormBoundarywAzv4TbhAz3AnBWx Content-Disposition: form-data; name:"image"; filename="IMG_20160113_112822899.jpg" Content-Type: image/jpeg

------WebKitFormBoundarywAzv4TbhAz3AnBWx Content-Disposition: form-data; name="image_data"

{"id":142,"updated_at":"2016-09-22 22:14:53","description":"Quidem odio fugit sit alias animi voluptates. Quo deserunt quas adipisci et dignissimos dolore est. Voluptas est debitis aut temporibus. Aut aut tempore consequuntur asperiores.","attribution":"Madge Moen","thumbnail_image_path":"whatever.jpeg","compressed_video_path":"sample.mp4","themes":[ ...omitted... ],"use_cases":[ ...omitted... ]} ------WebKitFormBoundarywAzv4TbhAz3AnBWx--

And here's my controller code:

public function update(Request $request, $id) {

    //$imageToUpdate = Image::where('id', $id)->firstOrFail();

    
    //$img = json_decode($request->image, true);

    dd($request->file('image'));

}

And all I get back as a response is "null"!

Any help would be appreciated! I've read similar questions but nothing I found has really solved my problem.

0 likes
2 replies
rdelorier's avatar
Level 9

When your content is multipart/form-data you are going to have to use the POST method with http method override using one of the following methods.

  • option A: use header 'X-HTTP-Method-Override': 'PATCH'
  • option B: form field: imgData.append('_method', 'PATCH')

Don't forget you can simplify your js by passing the form into the FormData constructor

var imgData = new FormData(document.querySelector('#myForm'))
simseag's avatar

Ah! Thank you so much! Option A worked for me.

Please or to participate in this conversation.