uniapp上传手机相册图片、视频或拍摄图片、视频上传

一开始想用现成组件uView的u-upload来实现,做到一半发现使用这个组件上传图片没有问题,可以满足从相册上传、直接拍摄、预览功能。但是,视频好像不支持预览,不知道是我写法不对还是怎么回事/(ㄒoㄒ)/~~

最终图片使用的u-upload组件,视频用了uniapp API 的 uni.chooseVideo()方法

一、上传或拍摄图片

<!-- 图片 -->
<view class="up-img">
    <view class="up-label">图片:</view>
    <u-upload :fileList="imgList" @afterRead="imgRead" @delete="deletePic" name="1" multiple :previewFullImage="true">
    </u-upload>
</view>
      // 新增图片
      async imgRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
        let lists = [].concat(event.file);
        let fileListLen = this.imgList.length;
        lists.map((item) => {
          this.imgList.push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        });
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadImg(lists[i], i);
          let item = this.imgList[fileListLen];
          this.imgList.splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            accessoryUrl: result
          }));
          fileListLen++;
        }
      },
      // 上传图片
      uploadImg(item, index) {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: baseUrl + `/md/quality/upload`, //需要传图片的后台接口
            filePath: item.url, // 上传图片 通过uni-app的uni-file-picker组件 函数返回
            name: 'file', //文件名字
            header: {
              'Authorization': "Bearer " + getToken(), //token
            },
            formData: {
              type: Object,
              default () {
                return {
                  file: item.name
                };
              }
            },
            success: res => {
              let result = JSON.parse(res.data);
              setTimeout(() => {
                resolve(result.accessoryUrl)
              }, 1000)
            },
            fail: e => {
              console.log(e)
            }
          });

        });
      },
      // 删除图片
      deletePic(event) {
        this.imgList.splice(event.index, 1);
      }

二、上传或拍摄视频

需要用到uni.chooseVideo 和 uni.uploadFile

详细用法参考

uni.chooseVideo(OBJECT) | uni-app官网

 uni.uploadFile(OBJECT) | uni-app官网

   <!-- 视频 -->
   <view class="up-video">
     <view class="up-label">视频:</view>
       <view class="up-video-box">
         <view class="v-box" v-show="videoList.length" v-for="(item,i) in videoList" :key="i">
          <view class="v-inner">
             <video style="width: 172px;height: 72px;" :src="item.accessoryUrl"></video>
          </view>
          <view class="c-icon">
             <u-icon @click="deleteVideo(i)" name="close" color="#fff" size="8"></u-icon>
          </view>
         </view>
         <view class="box-s" @click="videoRead">
            <u-icon name="camera-fill" color="#d3d4d6" size="26"></u-icon>
         </view>
       </view>
  <!-- <u-upload :fileList="videoList" @afterRead="videoRead" @delete="deleteVideo" name="2" multiple
            :previewFullImage="true" accept="video"></u-upload> -->
   </view>
     videoRead() {
        let that = this;
        let arr = [];
        let strPath = "";
        uni.chooseVideo({
          sourceType: ['camera', 'album'],
          success: function (res) {
            arr = res.tempFilePath.split("/");
            strPath = arr[arr.length - 1];
            that.videoList.push({
              accessoryUrl: res.tempFilePath,
              videoName: strPath
            });
            that.addUpload([{
              accessoryUrl: res.tempFilePath,
              videoName: strPath
            }]);
          }
        });
      },
      //文件提交上传
      addUpload(videoArr) {
        if (videoArr.length) {
          videoArr.forEach(item => { //这里之所以循环一个一个上传是因为,我是用于小程序端的,目前uniapp不支持微信小程序以文件列表形式上传,
            uni.uploadFile({
              url: baseUrl + `/md/quality/uploadVideo`, //需要传图片的后台接口
              filePath: item.accessoryUrl, // 上传图片 通过uni-app的uni-file-picker组件 函数返回
              name: 'file', //文件名字
              header: {
                'Authorization': "Bearer " + getToken(), //token
              },
              formData: {
                type: Object,
                default () {
                  return {
                    file: item.videoName
                  };
                }
              },
              success: res => {
                let result = JSON.parse(res.data);
                this.videoList.map(v => {
                 if(v.videoName === item.videoName) {
                   v["accessoryUrl"] = result.accessoryUrl;
                 }
                });
              },
              fail: e => {
                console.log(e)
              }
            });
          });
        }
      },
      deleteVideo(index) {
        this.videoList.splice(index, 1);
      }
    .up-video {
      display: flex;

      .up-video-box {
        width: calc(100% - 105px);
        display: flex;
        flex-wrap: wrap;

        .v-box {
          width: 185px;
          height: 82px;
          position: relative;
          overflow: hidden;
          margin: 0 8px 8px 0;
          padding: 10px 10px 0px 0px;
          box-sizing: border-box;
          background: #010101;

          .v-inner {
            position: absolute;
            bottom: 0px;
            left: 0px;
          }

          .c-icon {
            position: absolute;
            top: -7px;
            right: -7px;
            background: #373737;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 6px 6px 0px 0px;
            box-sizing: border-box;
          }
        }

        .box-s {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 80px;
          height: 80px;
          background-color: #f4f5f7;
          border-radius: 2px;
          margin: 0 8px 8px 0;
          box-sizing: border-box;
        }
      }

    }

tips: 代码里的baseUrl 是服务器地址 ip+端口完整地址, getToken()是获取token方法

三、效果展示

 这世界很喧嚣,做你自己就好

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Uniapp是一个跨平台的应用开发框架,可以同时开发出安卓、iOS和H5等多个平台的应用。在Uniapp中,我们可以使用一些插件来实现H5手机上传图片视频的功能。 对于图片上传,可以使用uni.uploadFile方法,通过选择图片后,将其以formData的形式上传到后端服务器。代码示例如下: ``` uni.chooseImage({ success: function (res) { uni.uploadFile({ url: 'http://example.com/upload', filePath: res.tempFilePaths[0], name: 'file', success: function (res) { console.log('图片上传成功'); }, fail: function (err) { console.error('图片上传失败', err); } }); } }); ``` 而对于视频上传,可以使用uni.chooseVideo方法选择要上传视频文件,然后使用uni.uploadFile方法将其上传到后端服务器。代码示例如下: ``` uni.chooseVideo({ success: function (res) { uni.uploadFile({ url: 'http://example.com/upload', filePath: res.tempFilePath, name: 'file', success: function (res) { console.log('视频上传成功'); }, fail: function (err) { console.error('视频上传失败', err); } }); } }); ``` 需要注意的是,上传文件需要后端服务器的支持,我们需要提前配置好后端接口来处理文件上传的请求。另外,在使用上传功能之前,需要先在uni-app的manifest.json配置文件中,将H5平台的origin字段配置为后端服务器的域名,以防止跨域问题的出现。 总结起来,Uniapp可以通过选择图片视频文件,再通过uni.uploadFile方法将文件上传到后端服务器,实现H5手机上传图片视频的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值