• Element文件上传-解决跨域


    以照片墙为例
    在这里插入图片描述
    官方源码

    
      
    
    
      
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    默认提交到action指定的url,如果是跨域的情况下。该方式是不支持的!

    需要使用 :http-request 的方式上传

    	
    		
    	
    	
    		
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    :http-request 指定自定义的方法,上传文件

    注意:action=“” 必须存在,给个空字符串即可。不能没有

    		upload(param) {
    			const formData = new FormData()
    			formData.append('file', param.file)
    			axios.post(url, formData).then(response => {
    				//根据返回值进行判断是否上传成功
    				if(response.data.flag){
    					//上传成功
    					console.log('上传图片成功')
    				}else{
    					//上传失败
    					console.log('图片上传失败')
    				}
    			}).catch(response => {
    				console.log('异常处理')
    			})
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    如果要限制上传文件的文件数,需要使用 :limit=“限制数”
    这儿:limit=“6” 设置了最大上传文件的数量为6

    	
    		
    	
    	
    		
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    有时我们需要对上传的文件进行格式限制,使用 :before-upload
    :before-upload=“beforeAvatarUpload” 在文件上传之前进行文件大小,格式等判断,是否允许上传

    	
    		
    	
    	
    		
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    这儿规定了只能上传对应格式的图片,和文件的大小
    返回true允许上传,false阻止上传

    			beforeAvatarUpload(file) {
    				const isJPG =
    						file.type === "image/gif" ||
    						file.type === "image/jpg" ||
    						file.type === "image/jpeg" ||
    						file.type === "image/png";
    				const isLt2M = file.size / 1024 < 1;
    				if (!isJPG) {
    					this.$message.error("仅支持gif,jpg,png格式的图片!");
    				}
    				if (!isLt2M) {
    					this.$message.error("上传图片大小不能超过 1MB!");
    				}
    				return isJPG && isLt2M;
    			}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    软件设计模式系列之六——单例模式
    【无标题】
    2022装备制造业服务数字化报告
    DC-5靶场下载及渗透实战详细过程(DC靶场系列)
    二分专题训练
    解密JavaChassis3:易扩展的多种注册中心支持
    vulnhub EMPIRE: BREAKOUT靶机
    linux下mysql的三种安装方法
    好用的在线思维导图软件--GitMind
    如何通过执行SQL为低代码项目提速?
  • 原文地址:https://blog.csdn.net/WEN38306482/article/details/127732909