uniapp开发微信小程序,小程序上传图片/视频到阿里云oss(调用接口的方式,让后端放)

<template>
  <McPage classes="min-h-full">
    <view>
      <view class="p-4 box-border">
        <view class="bg-white w-full rounded-3 center flex-col mt-12">
          <image :src="imgJoin(img)" class="w-80 h-80 rounded-2 mt--32rpx"></image>
          <view class="mt-4 text-#999AAC">{{ name }}</view>
          <view v-if="state*1 === 0" class="flex items-center mt-4 text-#999AAC text-xs">
            <text class="mr-3">描述相符</text>
            <u-rate
              v-model="rate"
              :count="5"
              size="38"
              :gutter="16"
              :min-count="1"
              active-color="#fdcb33"
              inactive-color="#999AAC"
              active-icon="star-fill"
              inactive-icon="star"
            />
            <text class="ml-3">{{ ['', '非常差','差','一般','好','非常好'][rate] }}</text>
          </view>
          <view class="w-full max-h-400 mt-2 p-2 box-border relative">
            <textarea
              v-model="commentContent"
              class="my-textarea"
              placeholder="从多个角度评价宝贝,可以帮助更多想买的人"
            />
          </view>
          <view v-if="imgList.length === 0" class="upData-box">
            <view class="upData">
              <view class="w-full h-full center flex-col" @click="clooseImage">
                <u-icon name="camera" size="32" color="black" class="mb-2"></u-icon>
                <text class="text-sm text-#222222">发图/视频能帮助他人更真实地了解商品</text>
              </view>
            </view>
          </view>
          <view v-else class="grid grid-cols-3 gap-3 py-4">
            <view
              v-for="(item, index) in imgList"
              :key="item.id"
              class="w-200 h-200 relative rounded-2 overflow-hidden"
            >
              <image v-if="item.contentType === 'image/jpeg'" :src="imgJoin(item.path)" class="w-full h-full" mode="aspectFill"></image>
              <image v-else :src="imgJoin(item.thumbTempFilePath)" class="w-full h-full" mode="aspectFill"></image>
              <image src="/static/image/icon/delet_img.png" class="absolute top-0 right-0 w-40 h-40" @click.stop="dltImg(item)"></image>
              <image v-if="item.contentType === 'video/mp4'" src="/static/image/icon/video2.png" class="videoIcon"></image>
            </view>
            <view v-if="imgList.length < 9" class="w-200 h-200 rounded-2 border-1 border-#E5E8EC border-dashed center flex-col" @click="clooseImage">
              <u-icon name="camera" size="32" color="black" class="mb-2"></u-icon>
              <text class="text-20 text-#222222 mt-2">照片/视频</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="fixed bottom-0 w-full left-0 p-4 box-border" @click="submit">
      <view class="bg-[--index-color] text-white w-full h-80rpx center rounded-full font-600">匿名发布</view>
    </view>

    <!--操作菜单  选择图片/视频-->
    <!--<u-action-sheet v-model="showAction" border-radius="24" :list="list" @click="clooseImage"></u-action-sheet>-->
  </McPage>
</template>

<script>
import { subYouGoodsOrderFirstPingjia, subYouGoodsOrderZhuiPingjia } from '@/api/mall'

export default {
  components: {},
  props: {},
  data() {
    return {
      id: '',
      name: '',
      img: '',
      state: '', // 0 首次评价 1 追评
      commentContent: '',
      orderData: {},
      rate: 0,
      imgList: [],
      showAction: false,
      list: [{
        text: '拍照',
      }, {
        text: '相册'
      }, {
        text: '视频'
      }],
    }
  },
  computed: {},
  watch: {},
  async onLoad(options) {
    this.id = options.id ? options.id : ''
    this.name = options.name ? options.name : ''
    this.img = options.img ? options.img : ''
    this.state = options.state ? options.state : ''
  },
  onShow() {},
  methods: {
    clooseImage() {
      const that = this
      if (this.imgList.length === 9) return
      uni.chooseMedia({
        count: 9 - this.imgList.length,
        sizeType: ['original', 'compressed'],
        // mediaType: mediaType,
        // sourceType: sourceType,
        mediaType: ['image', 'video'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success: res => {
          console.log(res)
          if (res.tempFiles.length === 0) return
          res.tempFiles.forEach(item => {
            console.log('item', item)
            that.$store.commit('SET_ANIMATION', true)
            uni.uploadFile({
              url: process.env.VUE_APP_BASE_API + 'api-file/files-upload',
              name: 'file',
              filePath: item.tempFilePath,
              header: {
                'Authorization': uni.getStorageSync('token'),
              },
              formData: {
                file: item,
                userType: 4,
                imgType: 'goods',
              },
              success: res => {
                console.log('res', res)
                if (res.statusCode === 200) {
                  const data = JSON.parse(res.data)
                  if (data.code === 200) {
                    console.log('data.data', data.data)
                    if (data.data.contentType === 'image/jpeg') {
                      this.imgList.push(data.data)
                    } else {
                      this.imgList.push({
                        ...data.data,
                        thumbTempFilePath: data.data.path + '?x-oss-process=video/snapshot,t_700,w_600,h_600,m_fast'
                      })
                    }
                  }
                }
              },
              fail: err => {
                console.log('err', err)
              },
              complete() {
                that.$store.commit('SET_ANIMATION', false)
              }
            })
          })
        },
      })
    },
    dltImg(item) {
      this.imgList = this.imgList.filter(e => e.id !== item.id)
    },
    async submit() {
      if (!this.commentContent) {
        uni.showToast({
          icon: 'none',
          title: '请填写评价内容',
        })
        return
      }
      const imgs = this.imgList.map(item => {
        if (item.contentType === 'image/jpeg') {
          return {
            type: 1,
            content: item.path,
          }
        } else {
          return {
            type: 2,
            content: item.path,
            coverImg: item.thumbTempFilePath
          }
        }
      })
      let res
      if (this.state * 1 === 0) {
        res = await subYouGoodsOrderFirstPingjia({
          orderDetailsId: this.id,
          score: this.rate,
          firstContent: this.commentContent,
          firstImgs: JSON.stringify(imgs),
        })
      } else if (this.state * 1 === 1) {
        res = await subYouGoodsOrderZhuiPingjia({
          orderDetailsId: this.id,
          firstContent: this.commentContent,
          zhuiImgs: JSON.stringify(imgs),
        })
      }
      if (res.code === 200) {
        // 从评价中心进来就直接返回评价中心
        const page = getCurrentPages()
        console.log('从评价中心进来就直接返回评价中心', page)
        if (page[page.length - 2].route === "pageMall/pages/comment/myComment") {
          uni.navigateBack()
          return
        }
        // 评价对象 : {type: 'comment', status: 1,}
        uni.setStorageSync('resultObject', {type: 'comment', status: 1, })
        uni.redirectTo({
          url: '/pageMall/pages/mall/result',
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .u-rate{
  gap: 10rpx;
}
.upData-box{
  width: 100%;
  padding: 32rpx;
  box-sizing: border-box;
  .upData{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 240rpx;
    border: 1px dashed #E5E8EC;
    border-radius: 20rpx;
    box-sizing: border-box;
  }
}
.videoIcon{
  width: 50rpx;
  height: 50rpx;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的微信小程序图片到阿里云OSS的例子: 1. 在微信小程序中,使用wx.chooseImage()方法选择需要上图片,并将其保存在本地变量tempFilePaths中。 ``` wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths; // 上图片到阿里云OSS uploadImage(tempFilePaths[0]); } }) ``` 2. 编写上图片的函数uploadImage(),其中需要设置header、formData、name、url等参数,并调用wx.uploadFile()方法上图片。 ``` function uploadImage(filePath) { // 阿里云OSS的Bucket名称和上文件夹名称 var bucketName = 'your-bucket-name'; var folderName = 'your-folder-name/'; // 生成上文件的唯一key var timestamp = new Date().getTime(); var key = folderName + timestamp + '-' + Math.floor(Math.random() * 10000) + '.jpg'; // 生成OSS的上接口地址 var policyBase64 = 'your-policy-base64'; var signature = 'your-signature'; var aliyunUrl = 'https://' + bucketName + '.oss-cn-hangzhou.aliyuncs.com'; // 设置header和formData var header = { 'content-type': 'multipart/form-data' }; var formData = { 'key': key, 'policy': policyBase64, 'OSSAccessKeyId': 'your-access-key-id', 'success_action_status': '200', 'signature': signature }; // 调用wx.uploadFile()方法上图片 wx.uploadFile({ url: aliyunUrl, filePath: filePath, name: 'file', header: header, formData: formData, success: function(res) { // 上成功,获取图片URL地址 var imageUrl = aliyunUrl + '/' + key; console.log('上成功,图片URL地址为:' + imageUrl); }, fail: function(res) { // 上失败 console.log('上失败:' + res.errMsg); } }) } ``` 需要注意的是,以上代码仅为一个示例,实际使用时需要按照阿里云OSS的规定进行设置,并在后端服务中编写相应的签名验证逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值