app-uploader.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. <template>
  2. <view>
  3. <div class="upload-box">
  4. <slot>
  5. <ul>
  6. <li class="list_img" v-for="(item,index) in showImgList" :key="index" :style="{ width: size + 'rpx', height: size + 'rpx' }">
  7. <div v-if="isMain" class="main-btn" :class="{'mian': index == 0}" @click.stop="mainImg(index)">主</div>
  8. <view class="iconfont icondelete" @click="delImg(index)"></view>
  9. <img :src="item" @click="viewImg(item)" :style="{ width: size + 'rpx', height: size + 'rpx' }" :mode="imgMode" />
  10. </li>
  11. <li v-if="showImgList.length < num && (multiple || showImgList.length == 0)" class="uploadImg" @click="chooseImage" :style="{ width: size + 'rpx', height: size + 'rpx' }">
  12. <view class="iconfont icontupiantianjia"></view>
  13. </li>
  14. </ul>
  15. </slot>
  16. </div>
  17. </view>
  18. </template>
  19. <script>
  20. import { uploadPic } from '@/api/common'
  21. export default {
  22. name: 'app-uploader',
  23. props: {
  24. // 传入的图片数组
  25. imgList: {
  26. type: Array,
  27. default: () => []
  28. },
  29. manualDel: {
  30. type: Boolean,
  31. default: false
  32. },
  33. // 图片的尺寸
  34. size: {
  35. type: Number,
  36. default: 200
  37. },
  38. // 上传图片数量
  39. num: {
  40. type: Number,
  41. default: 9
  42. },
  43. // 压缩图片
  44. compress: {
  45. type: Boolean,
  46. default: true
  47. },
  48. // 默认限制图片1.5M,单位为M
  49. maxSize: {
  50. type: String,
  51. default: '1.5M'
  52. },
  53. // 是否记录用户的选择记录
  54. isSave: {
  55. type: Boolean,
  56. default: false
  57. },
  58. // 记录用户的缓存字段
  59. saveStr: {
  60. type: String,
  61. default: 'chooseImage'
  62. },
  63. // 是否转base64 受数据传输长度限制,不建议在组件中使用,如果一定要使用,在返回结果中自己转换
  64. isBase64: {
  65. type: Boolean,
  66. default: false
  67. },
  68. multiple: {
  69. // 是否多图上传
  70. type: Boolean,
  71. default: true
  72. },
  73. disabled: {
  74. // 是否只读
  75. type: Boolean,
  76. default: false
  77. },
  78. // 图片展示模式
  79. imgMode: {
  80. type: String,
  81. default: 'scaleToFill'
  82. },
  83. uploadPicApi: {
  84. type: Function,
  85. default: uploadPic
  86. },
  87. // 是否显示主图切换
  88. isMain: {
  89. type: Boolean,
  90. default: false
  91. }
  92. },
  93. data() {
  94. return {
  95. resultData: {},
  96. showImgList: [],
  97. base64ImgList: [],
  98. xssarr: ['data:', 'text', 'txt', 'html', 'js', 'css', 'json', 'exe', 'sql', 'xml', 'doc', 'docx']
  99. }
  100. },
  101. onLoad() {
  102. if (this.isSave) {
  103. let str = uni.getStorageSync(this.saveStr)
  104. if (str !== '') {
  105. str = str.split(',')
  106. if (str.length > this.num) {
  107. str = str.slice(0, this.num)
  108. }
  109. this.showImgList = str
  110. }
  111. } else {
  112. uni.removeStorageSync(this.saveStr)
  113. }
  114. this.showImgList = [...this.imgList]
  115. },
  116. methods: {
  117. chooseImage: async function() {
  118. if (this.disabled) {
  119. return
  120. }
  121. let that = this
  122. let tempFilePaths = await that.getImage()
  123. await that.blobToBase64(tempFilePaths)
  124. await that.autoUploadImg()
  125. await that.postMsg()
  126. return this.showImgList
  127. },
  128. postMsg() {
  129. this.$emit('update:imgList', this.showImgList)
  130. this.$emit('chooseImage', this.showImgList)
  131. this.$emit('resultData', this.resultData)
  132. },
  133. autoUploadImg() {
  134. let that = this
  135. let base64ImgList = that.base64ImgList
  136. let params = {}
  137. if (base64ImgList.length === 1) {
  138. params['content'] = base64ImgList[0]
  139. } else {
  140. base64ImgList.forEach((item, index) => {
  141. params[`file[${index}][content]`] = item
  142. })
  143. }
  144. return new Promise((resolve, reject) => {
  145. this.uploadPicApi({
  146. ...params
  147. }).then(res => {
  148. if (res.code === 1) {
  149. let imgArr = [res.data.url]
  150. that.showImgList = [...that.showImgList, ...imgArr]
  151. that.resultData = res.data
  152. this.$emit('currentUpload', imgArr)
  153. this.$emit('getResult', that.showImgList)
  154. resolve(that.showImgList)
  155. } else {
  156. reject(res)
  157. }
  158. })
  159. })
  160. },
  161. // 转64
  162. async blobToBase64(tempFilePaths) {
  163. let that = this
  164. that.base64ImgList = []
  165. let newImgList = [...tempFilePaths]
  166. for (let i = 0; i < newImgList.length; i++) {
  167. let blob = newImgList[i]
  168. // 转64位后可以看文件类型 data:text/
  169. // #ifdef H5
  170. // 如果是服务器返回的图片不转base64
  171. // if (blob.indexOf('blob') !== 0) {
  172. // that.imgPathList.push(blob)
  173. // continue
  174. // }
  175. await that.h5b64(blob).then(res => {
  176. let startindex = res.indexOf(':')
  177. let endindex = res.indexOf('/')
  178. let type = res.substring(startindex + 1, endindex)
  179. if (that.xssarr.indexOf(type) === -1) {
  180. that.base64ImgList.push(res)
  181. }
  182. })
  183. // #endif
  184. // #ifdef MP-WEIXIN
  185. // 微信临时文件 http://tmp/wx3a16...
  186. // if (blob.indexOf('http://tmp/') !== 0) {
  187. // that.imgPathList.push(blob)
  188. // continue
  189. // }
  190. await that.WEIXINb64(blob).then(res => {
  191. that.base64ImgList.push(res)
  192. })
  193. // #endif
  194. }
  195. },
  196. WEIXINb64(blob) {
  197. return new Promise((resolve, reject) => {
  198. uni.getFileSystemManager().readFile({
  199. filePath: blob, // 选择图片返回的相对路径
  200. encoding: 'base64', // 编码格式
  201. success: function(res) {
  202. let b64str = 'data:image/jpeg;base64,' + res.data
  203. resolve(b64str)
  204. },
  205. fail: function(err) {
  206. console.log(err)
  207. }
  208. })
  209. })
  210. },
  211. h5b64(blob) {
  212. return fetch(blob, {
  213. method: 'GET',
  214. headers: new Headers({
  215. 'Access-Control-Allow-Origin': '*',
  216. 'Content-Type': 'text/plain'
  217. }),
  218. mode: 'no-cors'
  219. })
  220. .then(data => {
  221. const blob = data.blob()
  222. return blob
  223. })
  224. .then(async blob => {
  225. let reader = new FileReader()
  226. reader.readAsDataURL(blob)
  227. // return await new Promise((res, reg) => {
  228. // reader.onloadend = function() {
  229. // const data = reader.result
  230. // res(data)
  231. // }
  232. // })
  233. return await new Promise((res, reg) => {
  234. reader.onloadend = function() {
  235. let data = reader.result
  236. let str = data.substring(0, 30)
  237. if (str.indexOf(':image/jpeg;') == -1) {
  238. data = data.replace('data:;', 'data:image/jpeg;')
  239. }
  240. res(data)
  241. }
  242. })
  243. })
  244. },
  245. // 上传图片
  246. getImage() {
  247. let that = this
  248. let showImgList = that.showImgList
  249. let count = that.num - showImgList.length
  250. return new Promise((resolve, reject) => {
  251. uni.chooseImage({
  252. count: this.multiple ? count : 1, // 默认9
  253. sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  254. sourceType: ['album', 'camera'], // 从相册选择
  255. success: async function(res) {
  256. await that.fileValid(res)
  257. var tempFilePaths = res.tempFilePaths
  258. if (that.isSave) {
  259. uni.setStorageSync(that.saveStr, showImgList.join(','))
  260. }
  261. resolve(tempFilePaths)
  262. }
  263. })
  264. })
  265. },
  266. // 文件过滤
  267. fileValid(res) {
  268. let tempFiles = res.tempFiles
  269. let tempFilePaths = res.tempFilePaths
  270. let newtempFiles = []
  271. let newtempFilePaths = []
  272. for (let i = 0; i < tempFiles.length; i++) {
  273. // 大于1.5m就不让上传
  274. let fileSize = tempFiles[i].size
  275. if (fileSize > 1024 * 1024 * 1.5) {
  276. uni.showToast({
  277. title: '过滤不能大于1.5m的文件',
  278. duration: 2000,
  279. icon: 'none'
  280. })
  281. continue
  282. }
  283. // 文件类型设置
  284. let spl = tempFiles[i].path.split('.')
  285. let fileType = spl[spl.length - 1]
  286. if (fileType && this.xssarr.indexOf(fileType) >= 0) {
  287. uni.showToast({
  288. title: '过滤不符合规范文件',
  289. duration: 2000,
  290. icon: 'none'
  291. })
  292. continue
  293. }
  294. newtempFiles.push(tempFiles[i])
  295. newtempFilePaths.push(tempFilePaths[i])
  296. }
  297. res.tempFiles = newtempFiles
  298. res.tempFilePaths = newtempFilePaths
  299. // console.log('过滤完了')
  300. },
  301. // 设为主图
  302. mainImg(index) {
  303. if (index == 0) return false
  304. this.$msg('操作成功!')
  305. // let imgArr = JSON.parse(JSON.stringify(this.showImgList))
  306. let imgUrl = this.showImgList[index]
  307. this.showImgList.splice(index, 1)
  308. this.showImgList.unshift(imgUrl)
  309. // this.$emit('mainImg', index)
  310. this.postMsg()
  311. },
  312. // 删除
  313. async delImg(index) {
  314. if (this.disabled) {
  315. return
  316. }
  317. if (this.isSave) {
  318. uni.setStorageSync(this.saveStr, this.showImgList.join(','))
  319. }
  320. if (!this.manualDel) {
  321. this.showImgList.splice(index, 1)
  322. } else {
  323. this.$emit('delImage', index)
  324. }
  325. await this.postMsg()
  326. },
  327. // 预览
  328. viewImg(path) {
  329. uni.previewImage({
  330. urls: this.showImgList,
  331. current: path
  332. })
  333. },
  334. // 获取图片信息
  335. getImageInfo(image, cb) {
  336. uni.getImageInfo({
  337. src: image,
  338. success: function(image) {
  339. cb(image)
  340. return image
  341. }
  342. })
  343. },
  344. // 图片压缩
  345. compressImage() {
  346. uni.compressImage({
  347. src: image,
  348. quality: 80,
  349. complete: res => {}
  350. })
  351. }
  352. },
  353. watch: {
  354. imgList(val) {
  355. console.log('监听图片数据变化')
  356. this.showImgList = [...val]
  357. }
  358. }
  359. }
  360. </script>
  361. <style scoped lang="scss">
  362. .uni-system-preview-image {
  363. background-color: rgba(0, 0, 0, 0.9);
  364. .uni-preview-image {
  365. max-width: 100%;
  366. }
  367. }
  368. .upload-box {
  369. padding: 0 30px;
  370. &:first-child {
  371. padding-left: 0;
  372. }
  373. & > ul {
  374. display: inline-block;
  375. display: flex;
  376. flex-wrap: wrap;
  377. & > li {
  378. list-style: none;
  379. width: 210px;
  380. height: 210px;
  381. margin: 0 20px 20px 0;
  382. position: relative;
  383. background-color: #fff;
  384. .icondelete {
  385. font-size: 25px;
  386. z-index: 999;
  387. position: absolute;
  388. right: 0;
  389. bottom: 0;
  390. color: #fff;
  391. padding: 0 2px;
  392. background-color: rgba(0, 0, 0, 0.45);
  393. }
  394. .main-btn {
  395. position: absolute;
  396. top: 0;
  397. left: 0;
  398. z-index: 999;
  399. @include disFlex(center, center);
  400. width: 44px;
  401. height: 44px;
  402. background-color: #CCC;
  403. color: #fff;
  404. &.mian {
  405. background-color: $mainColor;
  406. color: #fff;
  407. }
  408. }
  409. }
  410. }
  411. & .list_img {
  412. & > img {
  413. width: 100%;
  414. height: 100%;
  415. }
  416. }
  417. & .uploadImg {
  418. border: 1px dashed #e5e5e5;
  419. display: flex;
  420. flex-direction: column;
  421. align-items: center;
  422. justify-content: center;
  423. box-sizing: border-box;
  424. .upload_ipt {
  425. position: absolute;
  426. width: 100%;
  427. height: 100%;
  428. /*overflow:hidden;*/
  429. cursor: pointer;
  430. opacity: 0;
  431. }
  432. .iconfont {
  433. color: rgb(150, 151, 153);
  434. font-size: 40px;
  435. }
  436. }
  437. }
  438. </style>