Vue3使用axios下载文件_axios 下载文件-CSDN博客

文章目录

概要

使用Axios请求下载接口,处理接口返回的blob数据,并在浏览器完成下载

前端统一封装请求类

import axios from 'axios';



const service = axios.create({
    baseURL: getBaseUrl(),
    timeout: 60000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    }
})

/**
 * <p>请求拦截器设置token
 */
service.interceptors.request.use(function (config) {
    config.headers['token'] = "token"
    if (config.method === 'post' || config.method === "POST") {
        //config.headers['Content-Type'] = 'text/plain;charset=UTF-8'
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    }
    return config
}, function (error) {
    console.log(error)
    return Promise.reject(error);
});


/**
 * <p>响应拦截器,处理全局信息
 */
service.interceptors.response.use(function (response) {
    const { status, statusText, data } = response;
    if (status === 200) {
        //此处判断是否下载请求
        if (response.headers['content-type'] === 'application/octet-stream') {
            //根据响应头获取文件名称
            let fileName = response.headers['content-disposition'].match(/filename=(.*)/)[1]
            if (fileName) {
                fileName = decodeURI(fileName)
            } else {
                //此处表示后台没有设置响应头 content-disposition,请根据业务场景自行处理
                fileName = "download.txt"
            }
            const blob = new Blob([response.data], { type: 'application/octet-stream' })
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                window.navigator.msSaveBlob(blob, fileName)
            } else {
                const blobURL = window.URL.createObjectURL(blob)
                const tempLink = document.createElement('a')
                tempLink.style.display = 'none'
                tempLink.href = blobURL
                tempLink.setAttribute('download', fileName)
                if (typeof tempLink.download === 'undefined') {
                    tempLink.setAttribute('target', '_blank')
                }
                document.body.appendChild(tempLink)
                tempLink.click()
                document.body.removeChild(tempLink)
                window.URL.revokeObjectURL(blobURL)
            }
        } else {
            //非下载请求返回的数据为json
            return response.data
        }
    } else {
        console.error(status, statusText, data)
    }
    return response;
}, function (error) {
    console.error(error)
    return Promise.reject(error);
});


export default service;


/**
 * <p>根据激活的环境获取回款系统的接口地址
 * @returns {*}
 */
export function getBaseUrl() {
    return "/api";
}

请求接口文件

import request from "../utils/request.js";

const API = {
    DEMO_URL: "/test",
    DOWNLOAD_URL: "/download"
}

/**
 * <p>返回json数据的方法
 * @param params
 * @returns {*}
 */
export function test(params) {
    return request({
        url: API.DEMO_URL,
        method: "GET",
        params
    })
}

/**
 * <p>下载文件的方法
 * @returns {*}
 */
export function download() {
    return request({
        url: API.DOWNLOAD_URL,
        method: "GET",
        responseType: 'blob' //此处设置为blob
    })
}

后台API接口

后台为SpringBoot脚手架生成的项目

package com.dataflow.web;

import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author CH
 * @Date 2024-03-05 19:53:13
 */
@RestController
public class DemoController {

    @GetMapping("/test")
    public Map<String, Object> test() {
        HashMap<String, Object> data = new HashMap<>();
        data.put("status", 200);
        data.put("data", "测试");
        return data;
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) {
        String fileName = "1.pptx";
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            //此处要对文件名进行URL编码,防止中文乱码
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            inputStream = Files.newInputStream(Paths.get("D://" + fileName));
            outputStream = response.getOutputStream();
            //此处使用工具类进行下载
            int copy = IOUtils.copy(inputStream, outputStream);
            response.addHeader("Content-Length",  copy + "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

Maven依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.1</version>
</dependency>

原网址: 访问
创建于: 2024-06-13 10:39:49
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论