Download Image via Ajax + Laravel

Asked

Viewed 477 times

0

I am trying to make a script for Download Images, by Ajax. It can be one or several. As you can see in JS, it has a function each searching for the selected images in the system. Then, I call Ajax to take as parameter the ID of the Photo for me to do a database search, search the address of the photo and download.

The code returns the encoded image instead of downloading. What do I need to change ? It is necessary to use AJAX ?

// Download de Imagens
   $("#download").click(function(){
      var ids = '';
      $("input[name='foto[]']:checked").each(function(){
         ids = $(this).val() + ',' + ids;
      });

      ids = ids.substr(0,ids.length-1);
      $.ajax({
         url: urlBase + '/portfolio/download/',
         cache: false,
         type: "POST",
         responseType: 'blob',
         data: {ids:ids}
      });
   });
# Download de Imagens 
public function anyDownload(){
  $ids = Input::get('ids');
  $imagem = GaleriaProjeto::find($ids);
  $headers = array(
    'Content-Type: image/jpg',
  );
  return Response::download(URL::to('/img/portfolio/'.$imagem->imagem, $imagem->imagem, $headers));
}
  • Use stacksnippet only to play problems with css, html and js that can be run.

1 answer

0


Solved, and I even made a scheme to zip the images.

 // Download de Imagens
   $("#download").click(function(){
      var ids = '';
      $("input[name='foto[]']:checked").each(function(){
         ids = $(this).val() + ',' + ids;
      });

      ids = ids.substr(0,ids.length-1);
      $.ajax({
         url: urlBase + '/portfolio/download/',
         cache: false,
         type: "POST",
         data: {ids:ids},
         success: function(result){
            if(result)
               window.location.href = urlBase + '/portfolio/baixar/'+result;
         }
      });
   });

php:

        # Download de Imagens 
        public function anyDownload(){
            $ids        = Input::get('ids');
            $imagem     = GaleriaProjeto::whereIn('id', explode(',', $ids))->get();

            $zipper = new \Chumper\Zipper\Zipper;
            $zipper->make('img/portfolio/imagens.zip');

            foreach($imagem as $arr){
                $zipper->add('img/portfolio/'.$arr->imagem);
            }
            return 'imagens.zip';
        }

        # Baixar Imagens
        public function getBaixar($slug){
            return Response::download('img/portfolio/'.$slug);
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.