You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.2 KiB

1 week ago
  1. <template>
  2. <view class="">
  3. <u-upload
  4. accept="image"
  5. :capture="['album', 'camera']"
  6. :fileList="fileList"
  7. @afterRead="afterRead"
  8. @delete="deletePic"
  9. :max-count="1"
  10. name="pet" width="60"
  11. height="60">
  12. <image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/image.png" style="width: 60px;height: 60px;">
  13. </image>
  14. </u-upload>
  15. </view>
  16. </template>
  17. <script>
  18. import { currentUrl } from '@/utils/getUrl'
  19. export default{
  20. data(){
  21. return{
  22. fileList:[]
  23. }
  24. },
  25. props:{
  26. imageUrl:{
  27. type:String,
  28. default:''
  29. }
  30. },
  31. mounted(){
  32. if(this.imageUrl){
  33. this.fileList=[{url:this.imageUrl}]
  34. }else{
  35. this.fileList=[]
  36. }
  37. },
  38. methods:{
  39. // 删除图片
  40. deletePic(event) {
  41. this.fileList.splice(event.index, 1)
  42. this.$emit('update:imageUrl', '');
  43. },
  44. // 新增图片
  45. async afterRead(event) {
  46. // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
  47. let lists = [].concat(event.file)
  48. let fileListLen = this.fileList.length
  49. lists.map((item) => {
  50. this.fileList.push({
  51. ...item,
  52. status: 'uploading',
  53. message: '上传中'
  54. })
  55. })
  56. const result = await this.uploadFilePromise(lists[0].url)
  57. if(result){
  58. this.fileList[0].status='success'
  59. this.fileList[0].message=''
  60. this.fileList[0].url=result
  61. }
  62. this.$emit('update:imageUrl', this.fileList[0].url);
  63. // for (let i = 0; i < lists.length; i++) {
  64. // const result = await this.uploadFilePromise(lists[i].url)
  65. // let item = this.fileList[fileListLen]
  66. // this.fileList.splice(fileListLen, 1, Object.assign(item, {
  67. // status: 'success',
  68. // message: '',
  69. // url: result
  70. // }))
  71. // fileListLen++
  72. // }
  73. },
  74. uploadFilePromise(url) {
  75. return new Promise((resolve, reject) => {
  76. uni.uploadFile({
  77. url: `${currentUrl}/h5/oss/upload`,
  78. filePath: url,
  79. name: 'file',
  80. formData: {
  81. user: 'test'
  82. },
  83. success: (res) => {
  84. setTimeout(() => {
  85. if(res&&res.data){
  86. let resData = JSON.parse(res.data);
  87. resolve(resData.url);
  88. }
  89. reject("上传失败");
  90. }, 1000)
  91. },
  92. });
  93. })
  94. },
  95. }
  96. }
  97. </script>
  98. <style></style>