• uniapp--点击上传图片到oss再保存数据给后端接口


    项目采用uniapp与uview2.0组件库

    --1.0的也可以参考一下,大差不差

    一、项目要求与样式图

    点击上传n张图片到oss,然后点击提交给后端

    二、思路

    1、打开上传按钮,弹出框内出现上传图片和提交按钮

    2、点击上传图片区域,打开本地图片或者调用相机。上传到oss拿到返回的图片url和本地的url地址。可以进行预览删除。再点击提交,将选取好的图片地址发送给后端就ok了

    一点特别注意,上传接口的方法一定要是POST,问就是小程序规定

    三、代码区域

    1. <view>
    2. <u-upload
    3. :fileList="fileList1"
    4. multiple
    5. @afterRead="afterRead1"
    6. @delete="deletePic1"
    7. name="1"
    8. :maxCount="3"
    9. width="175" height="175" >
    10. u-upload>
    11. //相关参数与公式去看view2的官方文档我就不一一简绍了
    12. <view>
    13. <button class="Upstatebtn" type="default" @click="UpdateStatus">提交button>
    14. view>
    15. view>
    16. //data参数
    17. //fileList1: [], //上传图片接受数组
    18. //img1: [], //当前图片数组
    因为使用方便,就直接复制的官网案例

    关键代码在添加图片后上传的两个数组处理和本地地址还有在线图片地址

    1. /**
    2. * @func 删除图片
    3. * */
    4. deletePic1(event) {
    5. this[`fileList${event.name}`].splice(event.index, 1)
    6. var arry = []
    7. this.fileList1.filter((v, i) => {
    8. arry.push(v.url)
    9. })
    10. this.img1 = arry
    11. console.log(this.img1, "1");
    12. },
    13. /**
    14. * @func 新增图片上传 读取后的处理函数
    15. * */
    16. async afterRead1(event) {
    17. // 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
    18. let lists = [].concat(event.file)
    19. console.log('list',lists);
    20. let fileListLen = this[`fileList${event.name}`].length
    21. lists.map((item) => {
    22. this[`fileList${event.name}`].push({
    23. ...item,
    24. status: 'uploading',
    25. message: '上传中'
    26. })
    27. })
    28. for (let i = 0; i < lists.length; i++) {
    29. const result = await this.uploadFilePromise1(lists[i].url)
    30. console.log('result是',result);
    31. let item = this[`fileList${event.name}`][fileListLen]
    32. this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
    33. status: 'success',
    34. message: '',
    35. url: result[0]
    36. }))
    37. fileListLen++
    38. }
    39. var arry = []
    40. this.fileList1.filter((v, i) => {
    41. console.log('每一个v是什么',v);
    42. arry.push(v.url)
    43. })
    44. this.img1 = arry
    45. console.log(this.img1, "1");
    46. },
    47. /**
    48. * @func 上传图片到oss,只提供files,后端完成上传
    49. * */
    50. uploadFilePromise1(url) {
    51. return new Promise((resolve, reject) => {
    52. let a = uni.uploadFile({
    53. url: '',//后端接口地址,后端解决了oss相关密钥获取
    54. filePath: url,
    55. name: 'files',
    56. success: (res) => {
    57. console.log(res.data);
    58. //这里使用JSON.parse是数据返回的问题需要进行转换,官网是不需要进行转换的,未了配合提交接口上传一个oss返回的图片列表数据
    59. console.log(JSON.parse(res.data));
    60. setTimeout(() => {
    61. resolve(JSON.parse(res.data).data) //服务器返回图片带域名
    62. //服务器返回图片不带域名需要自己拼接域名 否则预览图片无法实现
    63. // resolve('服务器域名' + JSON.parse(res.data).data)
    64. }, 1000)
    65. }
    66. });
    67. })
    68. },
    69. /**
    70. * @func 上传图片地址给后台端修改状态
    71. * */
    72. UpdateStatus() {
    73. let params = {
    74. id: this.Upid,
    75. fileList: this.img1
    76. }
    77. if (this.img1.length > 0) {
    78. //后端需要的数据格式,因为我自己循环时候做了调整不要要这个方法了。
    79. //后端要什么格式数据自己商定
    80. // params.fileList = this.img1.reduce((arr, cur) => arr.concat((cur), []))
    81. GetBudgetUpdate(params).then(res => {
    82. if (res == true) {
    83. //上传成功后清空params数据,关闭弹框,刷新列表,提示成功
    84. this.img1 = []
    85. this.taskList = []
    86. this.page = 1
    87. this.getBudgetList()
    88. this.showUp = false
    89. uni.showToast({
    90. title: `上传成功`,
    91. icon: 'none',
    92. duration: 2000,
    93. })
    94. }
    95. })
    96. } else {
    97. uni.showToast({
    98. title: `至少需要上传一张交付物图片`,
    99. icon: 'none',
    100. duration: 2000
    101. })
    102. }
    103. },
    104. /**
    105. * @func 上传图片取消,弹框关闭
    106. * */
    107. closePup(){
    108. this.showUp=false
    109. this.img1=[]
    110. this.fileList1=[]
    111. this.Upid=''
    112. },

    四、遇到的问题和处理

    第一次使用时候遇到一个问题是点击预览图片失败了,因为我点击图片传递调用uview组件源码方法所传递的值类型不一样    url: result[0]

    这一行代码卡了我这个菜鸡2天,我一直认为数据格式没问题,直接修改了下方的源码判断,,本来是url: result。直接添加了数组里的数组,然后传值给后端img1数组时候

    // params.fileList = this.img1.reduce((arr, cur) => arr.concat((cur), []))

    1. const a = [ ["1"],["2"],["3"],["4"] ]
    2. //变成
    3. const b =["1","2","3","4"]
    4.  const b = a .reduce((arr, cur) => arr.concat((cur), []));

    嵌套数组合并回去了


     

    1. for (let i = 0; i < lists.length; i++) {
    2. const result = await this.uploadFilePromise1(lists[i].url)
    3. console.log('result是',result);
    4. let item = this[`fileList${event.name}`][fileListLen]
    5. this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
    6. status: 'success',
    7. message: '',
    8. url: result[0]
    9. }))
    10. fileListLen++
    11. }

     uni.PreviewImage方法需要的是这样的数据格式,拿里面的url地址或者thumb地址

    1. // 预览图片
    2. onPreviewImage(item) {
    3. if (!item.isImage || !this.previewFullImage) return
    4. uni.previewImage({
    5. // 先filter找出为图片的item,再返回filter结果中的图片url
    6. urls: this.lists.filter((item) => this.accept === 'image' || uni.$u.test.image(item.url || item.thumb)).map((item) => item.url || item.thumb),
    7. current: item.url || item.thumb,
    8. // urls: this.lists.filter((item) => this.accept === 'image' || uni.$u.test.image(item.thumb || item.url)).map((item) => item.thumb || item.url),
    9. current: item.thumb || item.url,
    10. fail() {
    11. uni.$u.toast('预览图片失败')
    12. },
    13. });
    14. },

    五--感谢  小李小李,知书达理的思路与写法

    借鉴的这个文章

    uniapp利用uview2.0中的uploadFile组件实现多张图片的增删预览上传功能-CSDN博客

  • 相关阅读:
    算法通关村第三关|白银|双指针妙用【持续更新】
    【网络编程】UDP数据报套接字编程和TCP流套接字编程
    电路与数字逻辑期末复习重点整理!!
    网络安全(黑客)自学
    Go 语句与表达式深度解析
    jQuery常用API--效果
    [杂项]从子域名接管到Subtaker
    mac 上配置 git send-email
    Mac如何搭建Vue项目
    git如何将master分支合并到自己创建的分支
  • 原文地址:https://blog.csdn.net/a99101/article/details/134006884