关于前端进行文件上传和下载的一些细节

204 阅读1分钟

先说上传:

首先我是封装了一个el-upload的组件,先看代码:

<template>
    <el-upload
        class="upload-demo"
        ref="elUpload"
        action=""
        :show-file-list="false"
        :before-upload="beforeUpload"
        :http-request="uploadFile"
        multiple>
        <el-button size="mini">
            <i class="el-icon-upload2"></i>
            {{ name }}
        </el-button>
    </el-upload>
</template>
<script>
import { uploadFileApi } from '@/api/release';
export default {
    props: {
        name: {
            require: false,
            type: String,
            default: () => '导入'
        },
    },
    data () {
        return {
            upFile: new FormData(),
        };
    },
    created () {
    },
    methods: {
        beforeUpload (file) {
            if (file) {
                this.upFile.append('file', file);
            } else {
                return false;
            }
        },
        uploadFile () {
            uploadFileApi(this.upFile).then(res => {
                this.$emit('getPath', { path: res.data.path, type: this.type } );
                this.upFile = new FormData();
            }).catch(() => {
                this.upFile = new FormData();
            });
        },
    }
};
</script>
<style lang="scss" scoped>
.upload-demo {
    margin: 0 10px;
}
</style>

先讲一下v-upload这个组件吧,action是一个必须的参数,其中放的是你要上传文件的目标地址,但是如果说你的项目使用了代理,就会出现跨域和鉴权的一些问题,所以这里我将这儿置空,使用http-request这个方法,用自己的请求上传文件,

上传文件统一使用new ForData()的格式,在beforeUpload方法中将选中的文件append到对象中,

其次说一下后端返回文件流前端该如何下载的问题,代码如下:

 export default function download (res, name) {
    const content = res;
    const blob = new Blob([ content ]);//构造一个blob对象来处理数据
    const fileName = name;
    //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
    //IE10以上支持blob但是依然不支持download
    if ('download' in document.createElement('a')) { //支持a标签download的浏览器
        const link = document.createElement('a');//创建a标签
        link.download = fileName;//a标签添加属性
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();//执行下载
        URL.revokeObjectURL(link.href); //释放url
        document.body.removeChild(link);//释放标签
    } else { //其他浏览器
        navigator.msSaveBlob(blob, fileName);
    }
}

(注意:获取的文件流如果想是最新的,最好在每次请求的参数不同,最简单的办法就是加个字段,传值为new Date().getTime())

此处封装了一个js文件,res就是调取接口拿到的文件流,name是文件的名称,要带上文件后缀,