文件的上传和下载

上传采用的是FormData https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL
下载采用的是a标签的形式
import Axios from 'axios'

class Utils {
    downloadFile(url, params) {
        Axios.get(url, {
            params,
            responseType: "blob",
            headers: {
                Authorization: localStorage.getItem("token"),
            }
        }).then(res => {
            if (res.data) {
                let urls = window.URL.createObjectURL(res.data);
                let link = document.createElement("a");
                link.style.display = "none";
                link.setAttribute("download", "export.xls");
                link.href = urls;
                document.body.appendChild(link);
                link.click();
            }
        })
    }
    uploadFile(file, url) {
        return new Promise((resolve, reject) => {
            if (file) {
                let formData = new FormData();
                formData.append("file", file);
                Axios.post(url, formData, {
                    headers: {
                        "Content-type": "multipart/form-data",
                        Authorization: localStorage.getItem("token"),
                    }
                }).then(resolve).catch(reject)
            } else {
                reject(new Error('没有上传文件!'))
            }
        })
    }
}
export default new Utils();

import Utils from '../../Utils/Utils.js'
使用:

 // 下载
  let obj = Object.assign({}, this.queryInfo);
 // download.downloadFile("api/manager/corInvoice/export",obj)
 // 上传
 download.uploadFile(file, "api/manager/corInvoice/import")
        .then((res) => {
          if (res.status == 200) {
            this.$message.success("导入文件成功!");
            this.initTable();
          }
        })
        .catch((err) => {
          console.log(err);
        });

你可能感兴趣的:(前端vue.js)