如何使用axios使用html img/video标签显示图像或视频?

Asp*_*ian 0 c# typescript reactjs asp.net-core axios

我正在开发一个使用 axios 和 asp.net core 3.1 作为后端 api 的 React 应用程序(打字稿模板)。例如,我有这个受保护的(JWT 身份)端点来从服务器获取图像文件,如下所示FileStream

[Authorize(Policy = AspianCorePolicy.AdminAttachmentGetImagePolicy)]
[HttpGet("images/{filename}")]
public async Task<ActionResult> GetImage(string filename)
{
     var imageDto = await Mediator.Send(new GetImage.Query { FileName = filename });
     return File(imageDto.Memory, imageDto.MimeType, imageDto.FileName);
}
Run Code Online (Sandbox Code Playgroud)

考虑到,我也有一些大的视频文件要流式传输。

  • 话虽这么说,如果我想使用 Axios 将其作为文件流获取并将其显示在img标签中,甚至下载文件,我该如何通过 Axios 和 html 标签来做到这一点video?我应该使用 Axios吗?如果是这样,我到底该怎么做呢?responseType: 'stream'

Ale*_*ins 7

axios api 很简单。您可以在此处找到axios 浏览器示例

显示图像或视频非常相似。

设置调用以从 Web API 检索 Blob 响应。

var config = { responseType: 'blob' }
Run Code Online (Sandbox Code Playgroud)

然后进行调用并从 blob 创建数据 url。然后可以在目标元素上设置数据 url:

图像

axios.get("api/media?fileName=TestImage.png", config)
    .then(resp => {
        $("#img1").attr("src", window.URL.createObjectURL(resp.data));
    });
Run Code Online (Sandbox Code Playgroud)

视频

axios.get("api/media?fileName=TestVideo.mp4", config)
    .then(resp => {
        $("#video1").attr("src", window.URL.createObjectURL(resp.data));
    });
Run Code Online (Sandbox Code Playgroud)

下载将执行类似的过程,只不过您在 html 锚点元素上设置 href,并将 download 属性设置为 true。这可以通过编程方式完成,以在创建链接后单击链接(受此要点启发)

图像

axios.get("api/media?fileName=TestImage.png", config)
    .then(resp => {
        download(resp);
    });
Run Code Online (Sandbox Code Playgroud)

视频

axios.get("api/media?fileName=TestVideo.mp4", config)
    .then(resp => {
        download(resp);
    });
Run Code Online (Sandbox Code Playgroud)

以及下载功能

function download(resp) {
    var url = urlCreator.createObjectURL(resp.data);
    var fileName = resp.headers["content-disposition"].split("filename=")[1].split(";")[0];
    var link = document.createElement('a');
    $(link).attr("href", url).attr("download", fileName);
    link.click();
    window.URL.revokeObjectURL(url);
}
Run Code Online (Sandbox Code Playgroud)

就我而言,responseType: 'stream'我无法让它在浏览器中工作。根据 Axios Github,由于使用 XHR 请求,当前浏览器不支持流式传输。

将所有内容放在一起,并在您指定的路由上使用一个工作 Web API 端点,这将是工作代码示例。

var config = { responseType: 'blob' }
Run Code Online (Sandbox Code Playgroud)
axios.get("api/media?fileName=TestImage.png", config)
    .then(resp => {
        $("#img1").attr("src", window.URL.createObjectURL(resp.data));
    });
Run Code Online (Sandbox Code Playgroud)