2017-02-22 3 views
-1

Als ich eine Datei-Download-API entwickelt hatte ich fast nichts, um es in der HTML-Seite arbeiten zu lassen. Ich habe viel gesucht. Auf einigen Seiten habe ich herausgefunden, dass es unmöglich ist, mit Ajax herunterzuladen. Aber ich mache es möglich mit Ajax. Zuerst konvertieren Sie die Datei in base64, dann verwenden Sie dieses Stück Code als Middleware, dies wird Anker-Tag erstellen und beim Klicken wird Ihr Element für jede Art von Datei wie doc, docx, xls, xlsx, mp3, mp4 .... Es kann jede Art von Datei herunterladen.Laden Sie jede Datei mit jquery ajax

$(".filled-in").click(function(e) { 
    var _this=$(this); 
    $file = $(this).attr('id'); 
    $.ajax({ 
     type: "POST", 
     url: {!! json_encode(url('/download')) !!}, data: { 
      '_token' : $("input[name='_token']").val(), 
      'file' : $file 
     }, 
     dataType : "json", 
     success : function(json) { 
      var element = document.createElement('a'); 
      var fl='data:' + header_content +';charset=utf-8;base64,' +json.content; 
      element.setAttribute('href', fl); 
      element.setAttribute('download', $file_org_name); 
      element.click(); 
     } 
    }); 
}); 
+4

Was genau fragen Sie? –

+0

Darf ich fragen, welche Art von Sprache Sie mit Ihrer API erstellen? –

Antwort

1

NodeJS

const express = require('express') 
 
    ,app = express() 
 
; 
 
app.get('/download/:file*?', (req,res) => { 
 

 
    // Magic 
 
    ... 
 
    // Redirect your user to the file path, and let them download the file 
 
    res.download(`${__dirname}/${filePath}`); 
 
});

JavaScript

// Some kind of click event ¯\_(ツ)_/¯ 
 
buttonIGuess.addEventListener('click', e => { 
 
    // Create a invisible iframe for the file downloading 
 
    const iframeElement = document.createElement('iframe'); 
 
    // Set the source to your API and as well as the file path 
 
    iframeElement.src = 'https://pony.com/download/rainbow_dash.png'; 
 
}); 
 
// It should work, if is work :P