.Net Core WebAPI Axios Vue 实现下载与下载进度条

柔情似水 2024-03-29 ⋅ 16 阅读

在 Web 开发中,实现文件下载和显示下载进度条是一个常见的需求。在这篇博客中,我们将介绍如何使用 .Net Core WebAPI、Axios 和 Vue 来实现文件下载和显示下载进度条的功能。

准备工作

我们首先需要搭建一个基于 .Net Core 的 WebAPI 项目作为服务端,然后使用 Axios 来发送请求并下载文件,最后使用 Vue 来显示下载进度条。

创建 .Net Core WebAPI 项目

首先,我们需要安装 .Net Core 开发环境。具体可以参考官方文档进行安装。

然后,使用以下命令创建一个新的 .Net Core WebAPI 项目:

dotnet new webapi -n FileDownloadExample
cd FileDownloadExample

添加下载文件的 API

Controllers 文件夹下创建一个名为 DownloadController.cs 的控制器。代码如下:

using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace FileDownloadExample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DownloadController : ControllerBase
    {
        [HttpGet("{fileName}")]
        public IActionResult Download(string fileName)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads", fileName);

            if (!System.IO.File.Exists(filePath))
                return NotFound();

            var fs = new FileStream(filePath, FileMode.Open);

            return File(fs, "application/octet-stream", fileName);
        }
    }
}

该代码片段创建了一个 GET 请求的控制器方法,根据传入的文件名参数,构造出文件的路径并返回给客户端。

创建 Vue 项目并安装 Axios

首先,我们需要安装 Node.js。然后,使用以下命令全局安装 Vue CLI:

npm install -g @vue/cli

使用以下命令创建一个新的 Vue 项目:

vue create file-download-example
cd file-download-example

安装完毕后,我们处于 file-download-example 目录中。接下来,我们安装 Axios:

npm install axios --save

实现下载与下载进度条

配置 WebAPI 跨域

为了方便开发和测试,我们需要在服务端添加跨域配置。在 Startup.cs 中的 ConfigureServices 方法中添加以下代码:

services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});

Configure 方法中添加以下代码:

app.UseCors("AllowAll");

更新 Vue 组件

首先,我们准备一个下载按钮用于触发下载操作。在 src/components/HelloWorld.vue 中添加以下代码:

<template>
  <div class="hello">
    <button @click="downloadFile">下载文件</button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  methods: {
    downloadFile() {
      axios({
        url: 'http://localhost:5000/api/download/file.txt',
        method: 'GET',
        responseType: 'blob',
        onDownloadProgress(progressEvent) {
          let percentCompleted = Math.round(progressEvent.loaded * 100 / progressEvent.total)
          console.log(percentCompleted)
          // 显示下载进度条的代码
        }
      }).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'file.txt')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    }
  }
}
</script>

这段代码定义了一个名为 downloadFile 的方法,当点击下载按钮时会触发该方法。该方法使用 Axios 发送 GET 请求,并指定 responseTypeblob,表示希望响应返回二进制数据。在请求发送过程中,我们通过 onDownloadProgress 回调函数来处理下载进度条。具体的进度条显示逻辑可以根据实际需求自行编写。

运行项目

最后,我们可以运行整个项目了。首先,在 .Net Core WebAPI 项目的根目录下使用以下命令启动服务:

dotnet run

然后,在 Vue 项目的根目录下使用以下命令启动客户端:

npm run serve

打开浏览器,访问 http://localhost:8080/,点击下载按钮即可触发下载操作,并显示下载进度条。

总结

通过以上步骤,我们成功实现了在 .Net Core WebAPI + Axios + Vue 中下载文件和显示下载进度条的功能。这种组合是非常常见且流行的,能够满足大部分文件下载的需求。希望本文对你有所帮助!


全部评论: 0

    我有话说: