uniapp圖片上傳

一、寫入公共的上傳接口及環境common/config.js

const SystemConfig = {};

//版本號
SystemConfig.version  = "1.0";

//運行平臺
SystemConfig.platform = "uniapp";
SystemConfig.PLATFORM_MINIAPP_WX 	= "wexin";
SystemConfig.PLATFORM_APP_AD 		= "android";
SystemConfig.PLATFORM_APP_IOS 		= "ios";
SystemConfig.PLATFORM_WEB 			= "web";

//運行端
SystemConfig.CLIENT = "user";//用戶
SystemConfig.SHOP   = "shop";//商家

//上傳圖片接口
SystemConfig.uploadUrl = 'http://www.zi.cn:8080/upload/UploadImg';

export default SystemConfig;

二、封裝圖片上傳代碼upload_img.js

/*
	
	使用前先new 一下
	
	所有方法均返回 promise 對象 可使用then() 寫後續業務 或 使用 async await
	
	choose	選擇圖片
		參數 num 爲要選擇的圖片數量
	upload_one 上傳一張圖片
		參數 path  選擇成功後返回的 緩存文件圖片路徑
	upload  上傳多張圖片
		參數 path_arr 選擇圖片成功後 返回的圖片路徑數組
	choose_and_upload  選擇圖片並上傳
		參數 num 爲要選擇的圖片數量
		
*/

// 引入配置信息或者自己創建個 config 對象
import config from "@/common/config.js";

class Uploader {
	constructor() {
		
	}
	choose(num) {
	
	}
	
	upload_one(path,fileName,callback) {
		return new Promise((resolve, reject) => {

			uni.showLoading({
				title:'上傳中 0%'
			})
			console.log(config.uploadUrl)
			const uploadTask = uni.uploadFile({
					url: config.uploadUrl, //僅爲示例,非真實的接口地址
					filePath: path,
					name: fileName,
					success: (uploadFileRes) => {
						if("string"===typeof uploadFileRes.data){
							resolve(JSON.parse(uploadFileRes.data).data)
							console.log("uploadFileRes json-------")
							console.log(JSON.parse(uploadFileRes.data).data.id)
							var uploadImgId = JSON.parse(uploadFileRes.data).data.id;
						}else{
							resolve( uploadFileRes.data.data )
							console.log("uploadFileRes-------")
							console.log(uploadFileRes.data.data)
						}
						uni.showToast({
							title: '上傳成功',
							duration: 1000
						});
						
						callback(path,uploadImgId);
					},
					complete() {
						//uni.hideLoading()
					},
					fail() {
						uni.showToast({
							title: '上傳失敗',
							duration: 1000
						});
					},
				});
				
				
			uploadTask.onProgressUpdate((res) => {
				console.log('上傳進度' + res.progress);
				console.log('已經上傳的數據長度' + res.totalBytesSent);
				console.log('預期需要上傳的數據總長度' + res.totalBytesExpectedToSend);
				uni.showLoading({
					title:'上傳中 ' + res.progress + "%"
				})
				
			});	
		})
	}
	
	choose_and_upload(fileName,callback) {
		if(fileName == null){
			uni.showToast({
				title: '文件名錯誤',
				duration: 2000
			});
			return ;
		}
		
		let _this = this;
		//選擇文件
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'], //可以指定是原圖還是壓縮圖,默認二者都有,
			success(res) {
				console.log(res);
				
				if(res.tempFiles[0].size < 5100000){
					_this.upload_one(res.tempFilePaths[0],fileName,callback);
				}
				else{
					uni.showToast({
						title: '圖片過大',
						duration: 2000
					});
				}
			},
			fail(err) {
				console.log(err)
				reject(err)
			},
		})

	}
	
	
}
export default Uploader;

三、圖片上傳調用

<template>
<view class="ImgBox" @click="uploadGoodImg">
	<view class="upload" v-if="goodsData.imageName==''">
		<view class="ImgBox_top"><img src="@/static/img/shade_icon.png"  mode="widthFix" /></view>
		<view class="ImgBox_title">上傳</view>
	</view>
	<view class="uploadImg">
		<img class="uploader__img" :src="goodsData.imageName" :data-src="goodsData.imageName" style='width: 100%;' mode="widthFix"/>
	</view>
</view>
</template>

<script>
import upload from "@/common/upload_img.js"
export default {
 data() {
 	return {
 		userId:'',
 		goodsData:{goodsId:'',imageUrl:'',imageName:''},
 		uploadDisabled:false,//是否禁用圖片上傳
 	}
 },
 onLoad(options) {
 	//上傳圖片
	this.uploader = new upload ;
 },
 methods: {
 },
 mounted(){
 	// 上傳圖片
	uploadGoodImg(){
		if(this.uploadDisabled==false){
			this.num=1;//數量
			this.timestamp = this.userId + '/' + Date.parse(new Date()) ;//圖片名,與後臺約定
			this.uploader.choose_and_upload(this.timestamp,this.uploadScusse);
		}
	},
	//上傳成功
	uploadScusse(fileName,uploadImgId){
		console.log("callback"+fileName) 
		this.goodsData.imageName=fileName;
		this.goodsData.imageUrl=config.imgUrl+ this.userId + '/' + uploadImgId;;
	},
 }
}
</script>

<style>
	.ImgBox{
		height: 80px;
		width: 80px;
		border: 1px solid rgb(177, 177, 185);
		position: relative;
		top: 13px;
		overflow: hidden;
	}
	.ImgBox_top{
		width: 50px;
		height: 45px;
		margin: 10px auto 0;
		position: relative;
	}
	.ImgBox_title{
		height: 25px;
		line-height: 25px;
		text-align: center;
		font-size: 14px;
		color: #B1B1B9;
	}
	.ImgBox_top img{
		width: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}
</style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章