search

Home  >  Q&A  >  body text

How to download images using Vue.js and Laravel

I have a hyperlink button on click of this button and I want to get the image from the database and download it to the user side using laravel and vue js. Below is my script file code

getImage: function() {
            axios.get('/getImage/' this.form.cashout_id )
            .then(function (r)
                {
                const url = window.URL.createObjectURL(new Blob([r.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'file.' r.headers.ext); //or any other extension
                document.body.appendChild(link);
                link.click();

                //hide loader
                i.loader = false
            })
            .catch(function (error) {
                        alert('Error');
            });
        },

Now this is my controller code that is getting the image.

public function getimage($id)
   {
       $cashout = CashOutDetail::findormail($id);
       $storage_date = Carbon::parse($cashout['recorded_date']);

       return response()->download(
           storage_path('app/cashoutdetails/'. $storage_date->year .'/' . $storage_date->format('M') . '/'. $cashout->bank_receipt),
           'filename.jpg',
           ['Content-Type' => 'image/jpg']
       );
   }

The problem is that my image is being fetched and displayed in the console window, but not downloading. Can anyone help?

P粉513318114P粉513318114257 days ago475

reply all(1)I'll reply

  • P粉391677921

    P粉3916779212024-03-20 09:28:48

    你应该尝试:

    axios({
        method: 'GET',
        url: '/getImage/123.jpg',
        responseType: 'blob', // <-<<<<<<<<<< 
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '123.jpg');
        document.body.appendChild(link);
        link.click();
      });

    reply
    0
  • Cancelreply