Vant Uploader和axios结合上传图片到后台获取url

Vant Uploader和axios结合上传图片到后台获取url

html代码:

<van-uploader :after-read="afterRead" :upload-text="'上传图片'" :before-read="beforeRead" />

上传js代码:

/**
* 上传图片之后调用接口
*/
afterRead (file) {
    this.uploadImg(file.file)
},
/**
* 上传图片之前判断图片是否符合条件
*/
beforeRead (file) {
    if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('请上传 jpg/png 格式图片');
             return false;
    }
    let isLt1M = file.size / 1024 / 1024 <= 1
    if (!isLt1M) {
         Toast('图片大小1M以内');
         return false
    }
    return true;
},
/**
 * 上传图片
*/
uploadImg (file) {
	// 创建form对象
    let formdata1 = new FormData();
    // 通过append向form对象添加数据,可以通过append继续添加数据
    //或formdata1.append('file',file);
    formdata1.append('file', file, file.name);
    //设置请求头
    let config = {
         headers:{
             'Content-Type':'multipart/form-data'
         }
    };  
    //this.axios 是因为在main.js写在vue实例里
    const axiosAjax = this.axios.create({
         timeout: 1000 * 60, //时间
         withCredentials: true //跨域携带cookie
    });
    axiosAjax.post('url',formdata1,config).then((res)=>{   //这里的url为后端接口
        console.log(res.data);
        //res 为接口返回值
    }).catch(() => {})
}
发布了36 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/guoqiankunmiss/article/details/100015646
今日推荐