WeUI Uploader 组件属性upload 里的Promise回调传的参数究竟是?
发布于 6 年前 作者 yong09 6822 次浏览 来自 问答

copy https://developers.weixin.qq.com/miniprogram/dev/extended/weui/uploader.html 这里的代码

uplaodFile(files) {
        console.log('upload files', files)
        // 文件上传的函数,返回一个promise
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                reject('some error')
            }, 1000)
        })
    },

改成:

uplaodFile(files) {
        console.log('upload files', files)
        // 文件上传的函数,返回一个promise
        return new Promise((resolve, reject) => {
            setTimeout(() => {
              var object = {};
              object['urls'] = [files.tempFilePaths[0]]
 
              resolve({
                urls: object
              });
            }, 1000)
        })
    },

文档提示的就是这样写,没错啊

然后得到的错误是:

“TypeError: json.urls.forEach is not a function    at http://127.0.0.1:15186/appservice/libs/weui-miniprogram/uploader/uploader.js:237:51

不知掉那里出错了。痛苦啊

4 回复

最后改成数组传进去就没有错误提示了,但是同时带来新的错误

代码:

uplaodFile(files) {
  var that = this;
  console.log('upload files', files)
  // 文件上传的函数,返回一个promise
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // reject('some error')
      var object = {};
      object['urls'] = files.tempFilePaths[0]
 
      resolve({
        urls: [object]
      });
    }, 1000)
  })
},

错误提示:

应该是个bug,很大的bug

setTimeout只是模拟文件上传的过程,里面自己写

uplaodFile(files) {

    console.log(‘upload files’, files)

    let ps = [], up = (file)=>{

        return new Promise((resolve, reject) => {

            wx.uploadFile({

              url: 'https://example.weixin.qq.com/upload’, //仅为示例,非真实的接口地址

              filePath: file,

              name: ‘file’,

              success (res){

                // 服务器返回的数据 res.data = {url:‘图片上传后的地址’}

                if(res.data.url){

                    resolve(res.data.url)

                } else{

                    reject(res)

                }

              },

                fail(res){

                    reject(res)

                }

            })

        })

    }

    files.tempFilePaths.map((v)=>{

        ps.push(up(v))

    })

    return Promise.all(ps).then(res=>{

        return Promise.resolve({urls:res})

    }).catch(res=>{

        return Promise.reject(‘上传出错’)

    })

}

改成这样就解决了:

  uplaodFile(files) {
    console.log('upload files:', files)
    // 文件上传的函数,返回一个promise
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // reject('some error')
        resolve({
          urls: files.tempFilePaths
        });
      }, 1000)
    })
  },

uploadFile不管你怎么回调你console出来都是string字符串,你要在最后JSON.parse你的数据

回到顶部