vue el-upload 上传文件 action 跨域

本文介绍如何在Vue项目中使用el-upload组件避免跨域问题,通过自定义http-request属性实现图片上传,并包含文件类型及大小校验,确保上传过程符合业务需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:直接在action中写后端地址会出现跨域问题

解决:用http-request指定具体上传方法

el-upload代码如下,action中随便写,反正用不到

<el-upload
            class="avatar-uploader"
            action="string"
            :show-file-list="false"
            :http-request="uploadImage"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.picUrl" :src="form.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
// 上传图片方法
    uploadImage(param){
      const formData = new FormData()
      formData.append('file', param.file)
      uploadAvatar(formData).then(response => {
        console.log('上传图片成功')
        this.form.picUrl = process.env.VUE_APP_BASE_API + response.imgUrl
      }).catch(response => {
        console.log('图片上传失败')
      })
    },

上述代码中uploadAvatar方法如下

// 文件上传
request({
    url: '/system/file/upload',
    method: 'post',
    data: data
  })

照片上传前校验代码如下

// 资质照片上传前校验
    beforeAvatarUpload(file) {
      const isPic = file.type.indexOf('image') >= 0;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPic) {
        this.$message.error('资质照片只能为图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isPic && isLt2M;
    },

附加:上传方法为传递自定义参数 

:http-request="(param) => uploadImage(param,4)"

其中4为自定义参数

要实现Vue + Axios + El-upload进行文件上传,需要按照以下步骤进行操作: 1. 在Vue项目中安装axios和element-ui。在命令行中输入以下命令即可安装: ``` npm install axios element-ui --save ``` 2. 在Vue项目中创建一个上传文件的组件,例如FileUpload.vue。在该组件中导入axios和element-ui,并且引入El-upload组件。示例代码如下: ```vue <template> <div> <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :headers="headers" :data="formData" :file-list="fileList"> <el-button size="small" type="primary">点击上传</el-button> </el-upload> </div> </template> <script> import axios from 'axios' import { Message } from 'element-ui' export default { name: 'FileUpload', data () { return { fileList: [], uploadUrl: 'http://example.com/upload', formData: {}, headers: { 'Content-Type': 'multipart/form-data' } } }, methods: { handleUploadSuccess (response, file, fileList) { // 上传成功后的处理逻辑 console.log(response) }, beforeUpload (file) { // 文件上传前的处理逻辑 console.log(file) } } } </script> ``` 3. 在组件中实现文件上传的逻辑。在上传文件之前,需要设置请求头和请求数据,并且需要处理请求。可以在组件的methods中定义一个upload方法,用来发送上传请求。示例代码如下: ```vue <script> import axios from 'axios' import { Message } from 'element-ui' export default { name: 'FileUpload', data () { return { fileList: [], uploadUrl: 'http://example.com/upload', formData: {}, headers: { 'Content-Type': 'multipart/form-data' } } }, methods: { handleUploadSuccess (response, file, fileList) { // 上传成功后的处理逻辑 console.log(response) }, beforeUpload (file) { // 文件上传前的处理逻辑 console.log(file) }, upload () { let config = { headers: this.headers, withCredentials: true // 请求需要设置withCredentials为true } let data = new FormData() data.append('file', this.fileList[0].raw) // 向后端发送上传请求 axios.post(this.uploadUrl, data, config) .then(response => { this.handleUploadSuccess(response) }) .catch(error => { console.log(error) }) } } } </script> ``` 4. 最后,在Vue组件中使用El-upload组件,并且调用upload方法即可实现文件上传。示例代码如下: ```vue <template> <div> <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :headers="headers" :data="formData" :file-list="fileList"> <el-button size="small" type="primary" @click="upload">点击上传</el-button> </el-upload> </div> </template> <script> import axios from 'axios' import { Message } from 'element-ui' export default { name: 'FileUpload', data () { return { fileList: [], uploadUrl: 'http://example.com/upload', formData: {}, headers: { 'Content-Type': 'multipart/form-data' } } }, methods: { handleUploadSuccess (response, file, fileList) { // 上传成功后的处理逻辑 console.log(response) }, beforeUpload (file) { // 文件上传前的处理逻辑 console.log(file) }, upload () { let config = { headers: this.headers, withCredentials: true // 请求需要设置withCredentials为true } let data = new FormData() data.append('file', this.fileList[0].raw) // 向后端发送上传请求 axios.post(this.uploadUrl, data, config) .then(response => { this.handleUploadSuccess(response) }) .catch(error => { console.log(error) }) } } } </script> ```
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cesium vue

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值