【问题标题】:Download file served by ASP.NET Core using AJAX使用 AJAX 下载由 ASP.NET Core 提供的文件
【发布时间】:2019-03-26 22:16:50
【问题描述】:

我在 ASP.NET Core 上有返回文件的服务器代码:

    [HttpGet]
    [Route("update")]
    public IActionResult GetUpdate(int progId, string version)
    {
        var update = db.Updates.FirstOrDefault(u => u.ProgramId == progId && u.Version == version);
        if (update != null)
        {
            return new FileContentResult(update.Zip, "file/zip");
        }
        return BadRequest();
    }

我需要以某种方式使用 AJAX 下载它。 我试着这样做:

$('#testBtn').click(function () {
$.ajax({
    type: 'GET',
    url: 'https://localhost:44356/api/managment/update',
    data: 'progId=1&version=1.1',
    success: function(data) {
        const datafile = new Uint8Array(new Buffer(data));
        fs.writeFile('test.zip', datafile, (err) => {
            if (err) throw err;
            console.log('The file has been saved!');
        });
    }
})

还有更多不同的缓冲区和数组组合,但没有任何效果。

能否请任何人建议我应该怎么做,或者我哪里错了?

【问题讨论】:

  • 你提到了 Node.js,但那是客户端代码,使用 jQuery。我很困惑。
  • 您是否遇到任何错误或异常?
  • @MarcosCasagrande 这是电子。据我所知,electron 基于 node.js,对吧?
  • @Sean 不。文件的大小为 0 kb,或者在我使用 zip 存档的情况下,大小翻了一番,存档中有 1 个损坏的文件
  • 我想我遗漏了一些关于类型的东西,asp.net 核心 webapp 使用参数 update.Zip 形成 FileContentResult,它是字节数组,但我不知道,我在退出时有什么。

标签: javascript c# ajax asp.net-core


【解决方案1】:

经过一番研究,发现我可以从字节数组中返回base64字符串,然后轻松编写它。 服务器端(asp.net core 2.2):

    [HttpGet]
    [Route("update")]
    public string GetUpdate(int progId, string version)
    {
        var update = db.Updates.FirstOrDefault(u => u.ProgramId == progId && u.Version == version);
        if (update != null)
        {
            return Convert.ToBase64String(update.Zip);
        }
        return "failed";
    }

客户端(电子):

$.ajax({
    type: 'GET',
    url: 'https://localhost:44356/api/managment/update?progId=1&version=1.1',
    success: function(data) {
        fs.writeFile('test2.zip', data, {encoding: 'base64'}, (err) => {
            if (err) throw err;
            console.log('The file has been saved!');
        });
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2017-10-09
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多