uniapp上传图片和上传视频方法封装

uniapp上传图片和上传视频方法封装
新建一个utils.js文件,存放封装的方法
uniapp上传图片和上传视频方法封装_第1张图片
utils.js文件里面的方法如下:


import Config from '@/common/baseConfig.js';  //这个文件里面配置有上传文件地址
export default {
  
  /**
   * 图片选择加上传
   * @param number num
   * @param {Object} params
   * @param {Object} callback
   * @param string url
   * return array
   */
  upload: function(num, callback, url) {
  
  	var imgs_num = num;
  	var _self = this;
  	uni.chooseImage({
  		count: imgs_num,
  		sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
  		sourceType: ['album', 'camera'], //从相册或者拍照
  		success: async function(res) {
  			const tempFilePaths = res.tempFilePaths;
  			var imgs = [];
  			for (var i = 0; i < tempFilePaths.length; i++) {
  				var path = await _self.upload_file_server(tempFilePaths[i], '', url);
  				imgs.push(path);
  			}
  			typeof callback == 'function' && callback(imgs);
  		}
  	});
  },
  /**
   * 视频选择加上传
   * @param number num
   * @param {Object} params
   * @param {Object} callback
   * @param string url
   * return array
   */
  uploadVideo: function(callback, url) {
  	var _self = this;
  	uni.chooseVideo({
  		sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
  		sourceType: ['album', 'camera'], //从相册或者拍照
  		success: async function(res) {
        console.log(res)
  			const tempFilePaths = res.tempFilePath;
        
  			var path = await _self.upload_file_server(tempFilePaths, '', url);
  				
  			typeof callback == 'function' && callback(path);
  		}
  	});
  },
  //上传
  upload_file_server(tempFilePath, path, url = "") {
  	if (url) {
  		var uploadUrl = Config.upload
  	} else {
  		var uploadUrl = Config.upload
  	}
    console.log(tempFilePath)
    console.log(uploadUrl)
  	return new Promise((resolve, reject) => {
  		uni.uploadFile({
  			url: uploadUrl,
  			filePath: tempFilePath,
  			name: 'file',
  			success: function(res) {
  				var path_str = JSON.parse(res.data);
  				if (path_str.code >= 0) {
  					resolve(path_str.url);
  				} else {
  					reject("error");
  				}
  			}
  		});
  
  	});
  },
}

在项目根目录下的main.js文件里面引入并声明该文件:

import Utils from './utils/utils.js'
Vue.prototype.$utils = Utils;

在fabu.vue页面里面使用:

//上传图片
      uploadImg() {
       this.$utils.upload(9,res => {
         if(res.length>0) {
           res.forEach((v) => {
              this.img.push(v)
           })
         }
       })
      },
      //上传视频,默认一个
      uploadVideo() {
        this.$utils.uploadVideo(res => {
          if(res) {
            this.video = res;
          }
        })
      },
      //删除图片
      delImg(index) {
        this.img.splice(index,1)
      },

你可能感兴趣的:(uniapp,JavaScript,javascript,vue.js,前端)