前端通过后台接口下载文件

184 阅读1分钟

Get 请求接口

一般通过拼接完整接口链接(包含参数),然后设置a标签的href属性为链接,点击即可下载文件。

    <a
      style={{ color: '#2baee9' }}
      download
      href={`apiUrl`}
    >
        下载
    </a>

Post 接口请求

可以通过原生form标签的action属性下载文件,具体代码如下,input标签可以用来向请求中传递参数,参数名为name属性代表的值,参数值为value属性代表的值。

    <form
       style={{ display: 'inline-block' }}
       method="POST"
       target="_self"
       action={`apiUrl`}
    >
      <input type="hidden" name="fieldName" value="fieldValue" />
      <Button htmlType="submit" type="primary">
        下载
      </Button>
    </form>

通过转换blob下载文件

通过axios或类似的库调用接口时,设置responseType='blob',接口返回的body将会是一个blob对象

20221213152402.png

拿到数据后,对其进行转换,执行下载操作:

 let a = document.createElement('a');
 //注意,需要为文件设置一个名称
 a.download = fileName;
 a.href = URL.createObjectURL(res.body);
 a.click();