14

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

 3 years ago
source link: https://blog.csdn.net/weixin_44599931/article/details/111867147
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 || 'filename';
	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],
			   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);
 },

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK