chenqilong hace 1 año
padre
commit
06e599084b

+ 77 - 0
src/common/http/index.js

@@ -122,6 +122,83 @@ function del(url, data, loadingBool) {
   return $http(url, 'DELETE', data, true, loadingBool)
 }
 
+//封装的通用请求方法
+export const axios = function(obj = {}) {
+
+  console.log(666666);
+
+
+	if (typeof obj !== 'object') {
+		throw new Error('arguments must be object');
+	}
+	if (!obj.url) {
+		throw new Error('url not defined');
+	}
+	return new Promise((resolve, reject) => {
+		if (obj.isLoading) {
+			uni.showLoading({
+				title: '加载中',
+				mask: true,
+			})
+		}
+
+    console.log(77777);
+
+	let _url = process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + obj.url
+console.log(_url);
+  
+		let isGet = obj.method && obj.method.toLowerCase() == 'get';
+		let isQuery = obj.isQuery;
+		if (isGet || isQuery) {
+			_url += '?' + urlEncode(obj.params)
+		}
+		let _type = 'application/x-www-form-urlencoded';
+		if (obj.type == 'json') {
+			_type = 'application/json'
+		}
+		uni.request({
+			url: _url,
+			data: isGet || isQuery ? '' : (obj.params || ''),
+			header: {
+				'content-type': _type,
+				"x-token": store.getters.token,
+			},
+			method: obj.method ? obj.method : "POST",
+			success: function(ress) {
+        console.log(ress)
+
+				if (obj.isLoading) {
+					uni.hideLoading();
+				}
+
+        const res = ress.data;
+    if (whiteCodes.indexOf(res.code) < 0) {
+      
+
+      uni.showToast({
+        title: res.message || 'Error',
+        icon: 'none',
+        duration: 1500
+      })
+      reject(new Error(res.message || 'Error'));
+    } else {
+      resolve(res)
+    }
+
+			
+			},
+			fail: function(err) {
+				uni.hideLoading();
+				uni.showModal({
+					title: '提示',
+					content: '网络连接失败' + JSON.stringify(err),
+				})
+				reject(err);
+			},
+		})
+	})
+}
+
 export default {
   postJson,
   get,

+ 85 - 0
src/common/http/upload-file.js

@@ -0,0 +1,85 @@
+// fileUpload.js
+import { v4 as uuidv4 } from 'uuid'
+import axios from 'axios'
+import store from '@/store/index.js'
+
+/**
+ * @description: 文件附件上传
+ * file: 文件raw对象
+ * successCallback: 成功的回调函数
+ * errCallBack: 错误的回调函数
+ * progressCallback: 上传进度的回调函数
+ * dir: 上传阿里云目标文件夹 eg:图片image,视频video等
+ */
+const upload = async function (
+  file,
+  dir = 'image',
+  obj,
+  successCallback = new Function(),
+  errCallBack = new Function(),
+  progressCallback = new Function(),
+) {
+  let fileName = file.name
+
+  let config = {}
+  config.host = obj['host']
+  config.OSSAccessKeyId = obj['OSSAccessKeyId']
+  config.policyBase64 = obj['policy']
+  config.signature = obj['signature']
+  config.expire = parseInt(obj['expire'])
+  config.dir = obj['dir']
+  let fd = new FormData(),
+    uuid = uuidv4(),
+    key = `${config.dir}${uuid}${fileName}`
+  fd.append('key', key)
+  fd.append('success_action_status', '200')
+  fd.append('OSSAccessKeyId', config.OSSAccessKeyId)
+  fd.append('policy', config.policyBase64)
+  fd.append('signature', config.signature)
+  fd.append('success_action_status', '200')
+  fd.append('file', file)
+  console.log(config)
+  if (config.host.indexOf('http:') > -1) {
+    var protocol = window.location.protocol || 'http:'
+    var subUrl = config.host.substring(5, config.host.length)
+    config.host = protocol + subUrl
+  }
+  // 数据组装完成后,发送上传请求到阿里云oss
+  axios({
+    url: config.host,
+    method: 'POST',
+    data: fd,
+    processData: false,
+    cache: false,
+    contentType: false,
+    headers: {
+      'x-token':store.getters.token, // 请求头
+    },
+    // 这里,我们可以做上传经度
+    onUploadProgress: function (progressEvent) {
+      if (progressEvent.lengthComputable) {
+        let percent = (progressEvent.loaded / progressEvent.total) * 100 || 0
+        progressCallback({
+          percent: percent
+        })
+      }
+    }
+  })
+    .then(() => {
+      // 拿到结果后,做其他操作
+      let size =
+        file.size > 1000000
+          ? parseFloat(file.size / 1000000).toFixed(2) + 'M'
+          : parseFloat(file.size / 1000).toFixed(2) + 'KB'
+      successCallback({
+        attachment: fileName,
+        aliyunAddress: key,
+        size: size,
+        host: config.host
+      })
+    })
+    .catch(err => {
+      errCallBack(err)
+    })
+}
+export default upload

+ 54 - 4
src/common/utils/util.js

@@ -1,5 +1,7 @@
 import api from '@/common/http/'
+import { axios } from '@/common/http/'
 import store from '@/store/index.js'
+console.log(axios)
 
 // 获取用户信息
 export const getUserInfo = () => {
@@ -43,8 +45,7 @@ export const uploadImg = async function(file) {
     }).catch(err => {
       uni.hideLoading();
     })
-
-  const fileKey = par.dir + createName(file.name);
+  const fileKey = par.dir + createName(file.path);
 
   return new Promise((resolve, reject) => {
     const uploadTask = uni.uploadFile({
@@ -60,7 +61,6 @@ export const uploadImg = async function(file) {
       },
       filePath: file.path,
       success(res) {
-        console.log(res);
         resolve({
           data: {
             name: file.name,
@@ -129,8 +129,58 @@ export const getArea = function(str) {
 	return area;
 }
 
+// 图片上传
+export const uploadImgs = async function(file) {
+	uni.showLoading({
+		title: '上传中',
+		mask: true,
+	});
+
+	// 获取oss配置
+	const par = await axios({
+			url: '/common/oss/config',
+			method: 'get',
+		})
+		.then((res) => {
+			return res.data;
+		})
+		.catch((err) => {
+			uni.hideLoading();
+		});
+
+	const fileKey = par.dir + createName(file.path);
+
+	return new Promise((resolve, reject) => {
+		uni.uploadFile({
+			url: par.host,
+			// header: {
+			// 	"Content-Type": 'multipart/form-data',
+			// },
+			name: 'file',
+			formData: {
+				...par,
+				name: file.name,
+				key: fileKey,
+			},
+			filePath: file.path,
+			success(res) {
+				resolve({
+					url: fileKey,
+				});
+			},
+			fail(err) {
+				reject(err);
+			},
+			complete(res) {
+				uni.hideLoading();
+			},
+		});
+	});
+};
+
 export default {
   getUserInfo,
   uploadImg,
-  getArea
+  getArea,
+  uploadImgs
 };

+ 227 - 181
src/components/zj-upload/index.vue

@@ -1,189 +1,235 @@
 <template>
-	<view class="file-upload-container">
-		<view class="file-upload-view" v-for="(item,index) in files" :key="index">
-			<view class="file-upload-ckick" @click="imgView(index)">
-				<image v-if="item.url" mode="aspectFit" :src="imageUrl + item.url" style="width:100%;height:100%">
-				</image>
-				<template v-else>
-					<image mode="aspectFit" :src="item.loUrl" style="width:100%;height:100%">
-					</image>
-					<view class="mack" @tap.stop="()=>{}"></view>
-					<image @tap.stop="()=>{}" class="uploadImg" mode="aspectFit"
-						src="/static/upload/loading.png">
-					</image>
-				</template>
-				<image class="delImg" mode="aspectFit" src="/static/upload/del.png" @tap.stop="del(index)">
-				</image>
-			</view>
-		</view>
-		<view v-if="count===0?true:count-files.length" class="file-upload-view" @click="upload">
-			<view class="file-upload-ckick">
-				<image class="uploadImg" mode="aspectFit" src="/static/upload/upload.png">
-				</image>
-			</view>
-		</view>
-	</view>
+  <view class="file-upload-container">
+    <view class="file-upload-view" v-for="(item, index) in files" :key="index">
+      <view class="file-upload-ckick" @click="imgView(index)">
+        <image v-if="item.url" mode="aspectFit" :src="imageUrl + item.url" style="width: 100%; height: 100%"> </image>
+        <template v-else>
+          <image mode="aspectFit" :src="item.loUrl" style="width: 100%; height: 100%"> </image>
+          <view class="mack" @tap.stop="() => {}"></view>
+          <image @tap.stop="() => {}" class="uploadImg" mode="aspectFit" src="/static/upload/loading.png"> </image>
+        </template>
+        <image class="delImg" mode="aspectFit" src="/static/upload/del.png" @tap.stop="del(index)"> </image>
+      </view>
+    </view>
+    <view v-if="count === 0 ? true : count - files.length" class="file-upload-view" @click="upload">
+      <view class="file-upload-ckick">
+        <image class="uploadImg" mode="aspectFit" src="/static/upload/upload.png"> </image>
+      </view>
+    </view>
+  </view>
 </template>
 
 <script>
-	import {
-		uploadImg
-	} from "@/common/utils/util.js"
-	import {
-		b64_md5
-	} from "@/common/utils/md5.js"
-	import loadingImg from "./loading.png"
-	export default {
-		props: {
-			count: {
-				type: Number,
-				default: 0
-			},
-			fileList: {
-				type: Array,
-				default: () => []
-			}
-		},
-		data() {
-			return {
-				imageUrl: this.$imageUrl,
-				files: this.setFileVal(this.fileList)
-			};
-		},
-		watch: {
-			fileList() {
-				this.files = this.setFileVal(this.fileList)
-			},
-			files: {
-				handler(newName, oldName) {
-					if (newName.every(item => item.url ? true : false)) {
-						this.$emit("getFiles", newName.map(item => item.url))
-					}
-				},
-				deep: true
-			}
-		},
-		methods: {
-			setFileVal(arr) {
-				return arr.map(item => {
-					if (typeof(item) == 'string') {
-						return {
-							url: item,
-							key: b64_md5(item)
-						}
-					} else {
-						return item
-					}
-				})
-			},
-			upload() {
-				uni.chooseImage({
-					count: this.count === 0 ? 0 : this.count - this.files.length,
-					success: async res => {
-						const leng = res.tempFiles.length;
-						for (var file of res.tempFiles) {
-							this.files.push({
-								url: false,
-								key: b64_md5(file.path),
-								loUrl: file.path
-							})
-						}
-						for (var i = 0; i < leng; i++) {
-							var data = await uploadImg(res.tempFiles[i])
-							var obj = this.files.find(item => item.key === b64_md5(res.tempFiles[i]
-								.path))
-							if (obj) {
-								obj.url = data.url
-								obj.key = b64_md5(data.url)
-								delete obj.loUrl
-							}
-						}
-					},
-					fail: err => {
-						console.log(err);
-					}
-				})
-			},
-			del(index) {
-				this.files.splice(index, 1)
-			},
-			imgView(index) {
-				var list = this.files.map(item => {
-					if (item.url) {
-						return this.imageUrl + item.url
-					} else {
-						return loadingImg
-					}
-				})
-				uni.previewImage({
-					current: index,
-					urls: list
-				});
-			}
-		}
-	}
+// import { upload } from "@/common/http/upload-file.js";
+import api from '@/common/http/'
+import { uploadImgs } from '@/common/utils/util.js'
+import { b64_md5 } from '@/common/utils/md5.js'
+import loadingImg from './loading.png'
+export default {
+  props: {
+    count: {
+      type: Number,
+      default: 0
+    },
+    fileList: {
+      type: Array,
+      default: () => []
+    }
+  },
+  data() {
+    return {
+      imageUrl: this.$imageUrl,
+      files: this.setFileVal(this.fileList)
+    }
+  },
+  watch: {
+    fileList() {
+      this.files = this.setFileVal(this.fileList)
+    },
+    files: {
+      handler(newName, oldName) {
+        if (newName.every(item => (item.url ? true : false))) {
+          this.$emit(
+            'getFiles',
+            newName.map(item => item.url)
+          )
+        }
+      },
+      deep: true
+    }
+  },
+  methods: {
+    
+    setFileVal(arr) {
+      return arr.map(item => {
+        if (typeof item == 'string') {
+          return {
+            url: item,
+            key: b64_md5(item)
+          }
+        } else {
+          return item
+        }
+      })
+    },
+    upload() {
+      uni.chooseImage({
+        count: this.count === 0 ? 0 : this.count - this.files.length,
+        success: async res => {
+          //  #ifdef H5
+          uploadImgs(res.tempFiles[0]).then(res=>{
+            console.log(res);
+          })
+          //获取阿里oss上传参数
+      //     const par = await api.get('/common/oss/config').then(res => {
+      //       return res.data
+      //     })
+
+		  // console.log(res)
+
+      //     const blob = new Blob(res.tempFilePaths, { type: 'text/plain' })
+      //     console.log(par, blob)
+      //     const formData = new FormData()
+      //     formData.append('file', blob, 'dsff')
+
+      //     // 配置axios请求参数
+      //     const config = {
+      //       method: 'post',
+      //       url: par.host, // 根据你的存储桶所在地区修改域名
+      //       headers: {
+      //         'Content-Type': 'multipart/form-data'
+      //       },
+      //       data: formData
+      //     }
+
+		//   upload()
+
+          // 发送上传请求
+        //   try {
+        //     const response = await api('',config)
+        //     if (response.status === 200) {
+        //       console.log('上传成功')
+        //     } else {
+        //       console.log('上传失败', response)
+        //     }
+        //   } catch (error) {
+        //     console.log('上传发生错误', error)
+        //   }
+
+          //  #endif
+
+          // #ifdef MP-WEIXIN
+
+          // #endif
+
+          const leng = res.tempFiles.length
+          console.log(res)
+
+          return
+
+          for (var file of res.tempFiles) {
+            this.files.push({
+              url: false,
+              key: b64_md5(file.path),
+              loUrl: file.path
+            })
+          }
+          for (var i = 0; i < leng; i++) {
+            var data = await uploadImg(res.tempFiles[i])
+            console.log(data, this.files, b64_md5(res.tempFiles[i].path), 99)
+            var obj = this.files.find(item => item.key === b64_md5(res.tempFiles[i].path))
+            if (obj) {
+              obj.url = data.data.url
+              obj.key = b64_md5(data.data.url || '')
+              delete obj.loUrl
+            }
+          }
+        },
+        fail: err => {
+          console.log(err)
+        }
+      })
+    },
+    del(index) {
+      this.files.splice(index, 1)
+    },
+    imgView(index) {
+      var list = this.files.map(item => {
+        if (item.url) {
+          return this.imageUrl + item.url
+        } else {
+          return loadingImg
+        }
+      })
+      uni.previewImage({
+        current: index,
+        urls: list
+      })
+    }
+  }
+}
 </script>
 
 <style lang="scss" scoped>
-	.file-upload-container {
-		width: 100%;
-		height: 100%;
-		display: flex;
-		flex-wrap: wrap;
-		justify-content: space-between;
-
-		.file-upload-view {
-			display: inline-block;
-			margin-bottom: 20rpx;
-
-			&:nth-last-of-type(-n+2) {
-				margin-bottom: 0;
-			}
-
-			.file-upload-ckick {
-				width: 300rpx;
-				height: 190rpx;
-				background: #FFFFFF;
-				border-radius: 20rpx;
-				opacity: 1;
-				border: 1rpx solid #E4E4E4;
-				box-sizing: border-box;
-				padding: 10rpx;
-				position: relative;
-				display: flex;
-				justify-content: center;
-				align-items: center;
-
-				.mack {
-					width: 100%;
-					height: 100%;
-					position: absolute;
-					top: 50%;
-					left: 50%;
-					transform: translate(-50%, -50%);
-					z-index: 2;
-					background: rgba(0, 0, 0, 0.2);
-				}
-
-				.uploadImg {
-					width: 80rpx;
-					height: 80rpx;
-					position: absolute;
-					top: 50%;
-					left: 50%;
-					transform: translate(-50%, -50%);
-					z-index: 3;
-				}
-
-				.delImg {
-					position: absolute;
-					top: -16rpx;
-					right: -16rpx;
-					z-index: 2;
-					width: 40rpx;
-					height: 40rpx;
-				}
-			}
-		}
-	}
+.file-upload-container {
+  width: 100%;
+  height: 100%;
+  display: flex;
+  flex-wrap: wrap;
+  justify-content: space-between;
+
+  .file-upload-view {
+    display: inline-block;
+    margin-bottom: 20rpx;
+
+    &:nth-last-of-type(-n + 2) {
+      margin-bottom: 0;
+    }
+
+    .file-upload-ckick {
+      width: 300rpx;
+      height: 190rpx;
+      background: #ffffff;
+      border-radius: 20rpx;
+      opacity: 1;
+      border: 1rpx solid #e4e4e4;
+      box-sizing: border-box;
+      padding: 10rpx;
+      position: relative;
+      display: flex;
+      justify-content: center;
+      align-items: center;
+
+      .mack {
+        width: 100%;
+        height: 100%;
+        position: absolute;
+        top: 50%;
+        left: 50%;
+        transform: translate(-50%, -50%);
+        z-index: 2;
+        background: rgba(0, 0, 0, 0.2);
+      }
+
+      .uploadImg {
+        width: 80rpx;
+        height: 80rpx;
+        position: absolute;
+        top: 50%;
+        left: 50%;
+        transform: translate(-50%, -50%);
+        z-index: 3;
+      }
+
+      .delImg {
+        position: absolute;
+        top: -16rpx;
+        right: -16rpx;
+        z-index: 2;
+        width: 40rpx;
+        height: 40rpx;
+      }
+    }
+  }
+}
 </style>

+ 27 - 3
src/pages/issue/index.vue

@@ -1,4 +1,5 @@
 <template>
+  <!-- #ifdef H5 -->
   <view>
     <!-- ---须知--- -->
     <view>
@@ -20,7 +21,7 @@
           <u--input v-model="form.content" placeholder="请输入" border="none"></u--input>
         </u-form-item>
         <u-form-item label="商品图片" prop="form.name" borderBottom ref="item1">
-          <zj-upload key="cp" @getFiles="getFiles(index, $event)" :fileList="fileList" :count="1" />
+          <zj-upload key="cp" @getFiles="getFiles" :fileList="fileList" :count="1" />
         </u-form-item>
         <u-form-item labelPosition="left" label="商品分类" prop="form.categoryId" borderBottom ref="item1">
           <u-radio-group v-model="form.categoryId" placement="column">
@@ -91,11 +92,16 @@
       mode="year-month"
     ></u-datetime-picker>
   </view>
+  <!-- #endif -->
+  <!-- #ifndef H5 -->
+  <web-view :src="webViewHref('/pages/issue/index')"></web-view>
+  <!-- #endif -->
 </template>
 
 <script>
 import zjUpload from '@/components/zj-upload/index.vue'
 export default {
+  // #ifdef H5
   components: { zjUpload },
   data() {
     return {
@@ -128,10 +134,28 @@ export default {
     this.getDictList()
   },
   methods: {
-    getFiles() {},
+    getFiles(value) {
+      console.log(value, 67676)
+    },
     submin() {
       this.form.categoryName = this.categoryList.find(v => v.categoryId === this.form.categoryId)?.categoryName ?? ''
       console.log(this.form)
+      let params = {
+        ...this.form,
+        goodsFiles: [
+          {
+            goodsId: '',
+            imgUrl: '888888',
+            createTime: ''
+          }
+        ]
+      }
+      this.$api
+        .post('/goods/add',params)
+        .then(res => {
+            console.log(res);
+        })
+        .catch(() => {})
     },
     //获取商品分类数据
     async getList() {
@@ -155,7 +179,6 @@ export default {
         .catch(() => {})
     },
     handleDW() {
-        console.log(888);
       uni.chooseLocation({
         success: res => {
           this.form.lng = res.longitude
@@ -189,6 +212,7 @@ export default {
       this.show = false
     }
   }
+  // #endif
 }
 </script>