weixin_33726313 2016-01-01 01:29 采纳率: 0%
浏览 8

获取文件作为AJAX的回复?

I have a generic Ajax call routine that I use to call a function in node.js. This function reads a file from the server(xls mostly) then streams it back to client.

Here is my implementation in Node.js (server-side):

    // FILE DOESNT EXISTS BEFORE, 
    // FILE IS CREATED HERE THEN SAVED IN SERVER AS A FILE
    fs.readFile("/path/to/file.xlsx", function(err, file){
        res.setHeader('Content-Type', 'audio/mpeg');
        res.setHeader('Content-Disposition', 'attachment; filename=file.xlsx');
        res.write(file, 'binary');
        res.end();
    });

And this is my ajax call that I use.

$('#submit').click(function()
{
   $.ajax({
    url: '/',
    type:'POST',
    data: data,
    dataType: 'json',
    }).done(function(data) {
        console.log(data);
    });      
})

I successfully get binary data printed in my console (console.log(data)). My question is how to convert this data to a file with proper extension and then prompt the browser to save them ?

Any suggestion or another workaround ?

  • 写回答

1条回答 默认 最新

  • ~Onlooker 2016-01-01 01:38
    关注

    Try using FileReader , Blob , a element , download attribute

    $('#submit').click(function() {
       $.ajax({
        url: '/',
        type:'POST',
        data: data,
        dataType: 'json',
        }).done(function(data) {
            console.log(data);
            var reader = new FileReader();
            reader.onload = function(e) {
              $("a").attr({"href": e.target.result, "download":"filename"})
              .get().click()
            } 
            reader.readAsDataURL(new Blob([data]));
        });      
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器