2017-02-22 136 views
-1

当我开发一个文件下载API时,我几乎没有什么可以使它在html页面中工作。我搜索了很多。在一些页面中,我发现有些人说,使用ajax无法下载。 但我可以使用ajax。首先将文件转换为base64,然后使用这段代码作为中间件,这将创建锚点标记,点击后,您的元素将生成任何类型的文件,如doc,docx,xl​​s,xlsx,mp3,mp4 ....它可以下载任何类型的文件。使用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

你到底在问什么? –

+0

我可以问,你用什么类型的语言来构建你的API? –

回答

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