vue---文件的导入、导出及保存

文件上传:
1. headers: { “Content-Type”: “multipart/form-data” }
2. this.params = new FormData(); //创建form对象
this.params.append(“file”, file.raw); //通过append向form对象添加数据

<template>
        <el-form ref="dialogForm" :model="formParams" :rules="rules" size="small" label-position="right" label-width="100px">
            <el-form-item label="版本:" prop='version'>
                <el-input
                    v-model="formParams.version"
                    placeholder="请输入"
                    maxlength="200">
                </el-input>
            </el-form-item>
            <el-form-item label="来源" prop="source">
                <el-select v-model="formParams.source" placeholder="">
                    <el-option
                        v-for="item in sourceList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-upload
                ref="upload"
                action
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleUploadChange">
                <el-form
                    ref="dialogForm"
                    :model="file"
                    size="small"
                    label-position="left">
                    <el-form-item :label="'上传文件'+':'" class="is-required">
                        <div>
                            <el-input v-model="file.name"></el-input>
                            <el-button plain>上传</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-upload>
        </el-form>
        <div>
            <el-button @click="uploadFunc" :loading="submitloading">上传</el-button>
        </div>
</template>

<script>
import axios from "axios";
export default {
    methods: {
        handleUploadChange(file) {
            this.file = file;
            this.params = new FormData(); //创建form对象
            this.params.append("file", file.raw); //通过append向form对象添加数据
        },
        // 保存时,需要创建formData对象,往里面添加参数
        uploadFunc() {
            // 校验
            this.$refs.dialogForm.validate((valid) => {
                if (!this.$refs.upload.uploadFiles.length) {
                    this.$message({
                        type: 'info',
                        duration: '1500',
                        message: "请选择要上传的文件",
                        showClose: true
                    });
                }
                if (valid) {
                    let url = `${window.config.url}xxx`;
                    let config = {
                        headers: { "Content-Type": "multipart/form-data" }
                    };
                    this.params.append('version', this.formParams.version);
                    this.params.append('source', this.formParams.source);
                    axios.post(url, this.params, config).then(res => {
                        // 更新父组件数据
                        this.$emit('change', this.formParams)
                    }).catch(err => {
                        console.log(err);
                    })
                } else {
                    return false;
                }
            });
        }
    }
}
</script>

单个文件导出:

// res为导出接口传过来的二进制数据
downloadFile(res) {
        let _link = document.createElement('a');
        let _blob = new Blob([res]);
        _link.style.display = 'none';
        _link.href = URL.createObjectURL(_blob);
        _link.download = fileName;
        document.body.appendChild(_link);
        _link.click();
        document.body.removeChild(_link);
    }

压缩文件导出:
1. 如果axios中不加{}会导出会出现乱码的情况,或者下载下来的压缩包破损
2. 设置响应的数据类型为一个包含二进制数据的 Blob 对象,responseType: ‘blob’

axios({
                method: 'GET',
                url: `${window.config.url}xxx`,
                // 参数
                params: _params,
                responseType: 'blob'
            }).then(response => {
                // 不需要指定文件名时,可以直接使用window.location.href
                // window.location.href = url
                // 需要指定文件名的话,使用创建a标签的形式
                this.downloadZipFile(res);
            }).catch(error => this.$message.error(error) )
// 下载压缩包
    downloadZipFile(res, fileName = '') {
      let _fileName = res.headers['content-disposition'] ? decodeURI(res.headers['content-disposition'].split('filename=')[1]) : filename;
      if (res.data) {
        if ('msSaveBlob' in navigator) { // 对IE和Edge的兼容
          window.navigator.msSaveBlob(res.data, _fileName)
        } else {
          let blob = res.data;
          let a = document.createElement('a');
          a.setAttribute('id', 'exportLog');
          a.style.display = 'none';
          let url = window.URL.createObjectURL(new Blob([res.data]), { type: "application/zip" });
          let filename = _fileName;
          var evt = document.createEvent('HTMLEvents') // 对firefox的兼容
          evt.initEvent('click', false, false) // 对firefox的兼容
          a.href = url;
          a.download = filename;
          a.dispatchEvent(evt); // 对firefox的兼容
          a.click();
          window.URL.revokeObjectURL(url);
        }
      }
    },
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值