The 01/16/2017

Uploading an image via a REST API with Symfony 3 and Javascript

Today I wanted to upload an image via a REST API, via the PUT and POST methods, I had some difficulties to do so then I share how I did this with Symfony3. I think it will surely serve others.

Send an image via a REST API to PUT or POST ... the principles

In POST, you will be able to recover the file if you send well in multipart-form-data and it is rather practical but I will not use this in my case. The second option to transfer an image without sending a file directly is to encode it in base64 before sending it and then retrieve it after sending it to store it in BDD (or reconvert it and save it if necessary). In this way I will be able to upload my images in PUT also .... and since I type on a REST API is rather important to know to do because the editions of my objects will be done in PUT.

Retrieve the base64 image and update the thumbnail

I put an area below my fields to preview what I'll upload:

 <img id="logo-demo" src="" />
 
With each change of my input type = "file", I will call the previewThumbnail method which will update the src attribute of my preview image:

previewThumbnail: function(event){
    var input = event.target;

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#logo-demo').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

Save my image via REST API PUT

In the code above, I read the image selected in the input and I update the src attribute with the result in base64. The image will then be displayed each time a picture is selected. After each click on the "save" button on my form, before saving my form, I update my Model by retrieving the src attribute like this:

 saveEnterprise: function(event) {
            event.preventDefault();
            this.mymodel.image = $('#logo-demo').attr('src');
            axios.put('/api/mymodel/' + this.mymodel.id, this.mymodel)
                .then(function (response) {

                })
                .catch(function (error) {
                    alert(error);
                });
        },
        
I then use axios to send my request in PUT to my API REST. Here you have the principles, it's up to you to adapt to your code now :) If you have better solutions it will be with pleasure that I will listen to you. As you know I am still beginner with Symfony.
Comments on this article
No comments yet for this article. Be the first !

You must be logged in to comment an article.