首页 > 其他分享 >elementUI中upload自定义上传行为 http-request属性

elementUI中upload自定义上传行为 http-request属性

时间:2023-06-27 16:56:41浏览次数:34  
标签:const 自定义 elementUI url data error http message config

需求是上传一个xlsx后台处理完再返回xlsx流upload 请求需要添加responseType: 'blob' 属性所有要扩展一下

若依项目扩展elementUI中upload自定义上传行为 http-request属性

        <el-upload ref="upload1" :limit="1" accept=".xlsx, .xls"
                   :headers="upload1.headers" :data="formUpload"
                   action=""
                   :disabled="upload1.isUploading"
                   :http-request="uploadFile"
                   :on-success="handleFileSuccess"
                   :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em>
            <div style="font-size: 12px;">仅允许导入xls、xlsx格式文件。</div>
          </div>
        </el-upload>

data数据

        upload1: { 
          // 是否显示弹出层(用户导入)
          open: false,
          // 弹出层标题(用户导入)
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
        
          
        },

Method方法

  //参数必须是param,才能获取到内容
      uploadFile(param){
        // 获取上传的文件名
        var file = param.file
        //发送请求的参数格式为FormData
        const formData = new FormData();
        formData.append("file",file)
        // 调用param中的钩子函数处理各种情况,这样就可以用在组件中用钩子了。也可以用res.code==200来进行判断处理各种情况
        this.startUploadFile(formData,param).then(res=>{
          param.onSuccess(res)
        }).catch(err=>{
          param.onError(err) }
        ) },


      // 上传的请求(这里是request封装的请求,封装了请求头等信息) responseType: 'blob' 这个是关键
      //request是封装的请求方法
      startUploadFile(query,param){
        return request({
          url: "/checkmodel/dataManage/fillAddress",
          responseType: 'blob',
          method:'post',
          data: query,
        })
      },

// 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.anhaoOpen = false;
        const blob = new Blob([response])
        saveAs(blob, "模板.xlsx")
      },

以下是请求的全文件

import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils/ruoyi";
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'

let downloadLoadingInstance;
// 是否显示重新登录
export let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 对应国际化资源文件后缀
axios.defaults.headers['Content-Language'] = 'zh_CN'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项,表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    }
    const sessionObj = cache.session.getJSON('sessionObj')
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      cache.session.setJSON('sessionObj', requestObj)
    } else {
      const s_url = sessionObj.url;                  // 请求地址
      const s_data = sessionObj.data;                // 请求数据
      const s_time = sessionObj.time;                // 请求时间
      const interval = 1000;                         // 间隔时间(ms),小于此时间视为重复提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
        const message = '数据正在处理,请勿重复提交';
        console.warn(`[${s_url}]: ` + message)
        return Promise.reject(new Error(message))
      } else {
        cache.session.setJSON('sessionObj', requestObj)
      }
    }
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
        MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
          isRelogin.show = false;
          store.dispatch('LogOut').then(() => {
            location.href = process.env.VUE_APP_CONTEXT_PATH + "index";
          })
      }).catch(() => {
        isRelogin.show = false;
      });
    }
      return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
    } else if (code === 500) {
      Message({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code === 601) {
      Message({ message: msg, type: 'warning' })
      return Promise.reject('error')
    } else if (code !== 200) {
      Notification.error({ title: msg })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误,请联系管理员!')
    downloadLoadingInstance.close();
  })
}

export default service


标签:const,自定义,elementUI,url,data,error,http,message,config
From: https://www.cnblogs.com/zh76412950/p/17509333.html

相关文章

  • 如何高度优化适用于企业自定义的AI (一) 序言
    概述在当前信息时代的背景下,社会对AI的需求在不断增长.AI的快速发展得益于大数据、云计算和计算能力的提升,使得机器学习和深度学习等技术取得了重大突破.AI在图像识别、语音识别、自然语言处理等领域展现出惊人的能力,为企业带来了巨大的商机.然而,通用的AI解决方案无法......
  • elementui admin项目中使用echarts
    1.引入依赖npminstallecharts--save2.在template中写<template>  <div>   <el-card>    <divid="mychart":style="{height:height,width:width}"></div>   </el-card>  </div></t......
  • elementui admin中使用外部链接 iframe进行页面的展示
    有时候我们需要外部链接进行展示而且想要这个外部链接的页面不是打开新窗口而是嵌入在项目布局中,就需要用到iframe控件了,iframe控件不需要安装依赖包,可以直接使用1.在template中写<template>  <div>    <iframe:src="linkUrl"frameborder="0":style="{'heig......
  • 直播开发app,vue防抖 自定义ref实现输入框防抖
    直播开发app,vue防抖自定义ref实现输入框防抖 首先需要把input的双向绑定v-mode拆开为一个value和一个input事件,在事件里注册一个函数debUpdata,debUpdata里获取到input输入内容再赋值给text,这就类似于手写v-mode,代码如下: <template> <divclass="hello">  <inpu......
  • 基于vue+elementUI使用vue-amap高德地图
    首先,需要去高德地图进行注册一个https://lbs.amap.com/?ref=https://console.amap.com/dev/index,得到一个key然后安装依赖npminstallvue-amap—save在main.js中加入importVueAMapfrom'vue-amap’;Vue.use(VueAMap);VueAMap.initAMapApiLoader({key:'YOUR_KEY’......
  • 【HarmonyOS】低代码开发使用module中的自定义组件
     “Module是应用/服务的基本功能单元,包含了源代码、资源文件、第三方库及应用/服务配置文件,每一个Module都可以独立进行编译和运行。一个HarmonyOS应用/服务通常会包含一个或多个Module,因此,可以在工程中创建多个Module,每个Module分为Ability和Library两种类型。”这个是HarmonyOS......
  • 模拟HTTP测试post请求与get请求方式的工作原理与抓包分析
    一,工作原理与简介HTTP请求是客户端向服务器发送请求的过程,常见的HTTP请求方法有GET和POST。如下图,HTTP新建请求过程(1)GET请求的工作原理是,客户端向服务器发送一个请求,请求中包含要获取的资源路径和参数,服务器根据路径和参数返回相应的资源。GET请求可以在URL中传递参数,参数以键......
  • tcpdump捕获网络http流量
    tcpdump-iany-s0-A|egrep-i"POST/|GET/|Host:" 这个命令将使用tcpdump捕获网络流量,并过滤出包含POST、GET和Host字段的流量。具体各选项的含义如下:*`-iany`:捕获任何网络接口的流量。*`-s0`:指定抓包时每个数据包的只捕获前0个字节,即只捕获数据包的头部信息,......
  • Spring REST 接口自定义404不能捕获NoHandlerFoundException问题
    SpringREST接口自定义404以及解决不能捕获NoHandlerFoundException问题  一、自定义404响应内容版本说明:SpringBoot2.0.1.RELEASEREST风格默认PostMan请求的404响应如下:{"timestamp":"2018-06-07T05:23:27.196+0000","status":404,"error":&quo......
  • Android自定义控件
    继承现有控件类publicclassLeftButtonBarextendsLinearLayout{//默认实现的构造函数beginpublicLeftButtonBar(Contextcontext){super(context);}publicLeftButtonBar(Contextcontext,@NullableAttributeSetattrs){supe......