UNI-APP_uni-app上传文件方法封装

1.更目录新建文件 utils/index.js

index.js

import {
	TOKENNAME,
	HTTP_REQUEST_URL
} from '../config/app'
export default{
	/*
	 * 单图上传
	 * @param object opt
	 */
	uploadImageOne: function(opt, successCallback, errorCallback) {
		let that = this;
		if (typeof opt === 'string') {
			let url = opt;
			opt = {};
			opt.url = url;
		}
		let count = opt.count || 1,
			sizeType = opt.sizeType || ['compressed'],
			sourceType = opt.sourceType || ['album', 'camera'],
			is_load = opt.is_load || true,
			uploadUrl = opt.url || '',
			inputName = opt.name || 'pics',
			fileType = opt.fileType || 'image';
		uni.chooseImage({
			count: count, //最多可以选择的图片总数  
			sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有  
			sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有  
			success: function(res) {
				console.log('res: ', res.tempFilePaths[0]);
				//启动上传等待中...  
				uni.showLoading({
					title: '图片上传中',
				});
			   uni.uploadFile({
				   url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
				   filePath: res.tempFilePaths[0],
				   fileType: fileType,
				   name: inputName,
				   formData: {
					   'filename': inputName
				   },
				   header: {
					   // #ifdef MP
					   "Content-Type": "multipart/form-data",
					   // #endif
					   [TOKENNAME]: "用户token"
				   },
				   success: function(res) {
					   console.log(res,'res22222222222222')
					   uni.hideLoading();
					   if (res.statusCode == 403) {
							uni.showToast({
								title: res.data,
								icon:"none",
								duration: 2000
							});
						} else {
							let data = res.data ? JSON.parse(res.data) : {};
							if (data.status == 200) {
								successCallback && successCallback(data)
							} else {
								errorCallback && errorCallback(data);
								uni.showToast({
									title: data.message,
									icon:"none",
									duration: 2000
								});
							}
						}
				   },
				   fail: function(res) {
					   uni.hideLoading();
					   	uni.showToast({
							title: '上传图片失败',
							icon:"none",
							duration: 2000
						});
				   }
			   })
			}
		})
	},
}

main.js

import Vue from 'vue'
import App from './App.vue'
import utils from 'utils'

Vue.prototype.$util = utils		//挂载到原型

Vue.config.productionTip = false

const app = new Vue({
	store,
    ...App
})
app.$mount()

使用

//上传调用
 uploadpic: function() {
 	let that = this;
 	console.log('地方');
 	that.$util.uploadImageOne('upload/image', function(res) {
 		console.log(res);
 		that.pics.push(res.data.path);
 	});

 },
 //删除
 DelPic: function(index) {
 	let that = this,
 	that.pics.splice(index, 1);
 },
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值