uniapp 上传图片,视频,文件 到阿里云oss (egg.js后端)

时间:2024-03-11 14:01:52

直接上代码:(博客中红色标注请注意)

1.前端(分为两个部分,选择图片和上传图片)

前端代码,用到了uni-app中的drawer(抽屉)组件,大家自定义一个点击事件即可。

 效果图

<uni-drawer class="drawer" ref="drawer" mode="right">
   <view class="drawer-top"></view>
   <view @click="upLoadImg" class="dra-item"><view style="font-size: 20px;color: #dcdcdc;" class="iconfont icon-picture icon"></view>上传图片</view>
   <view @click="upLoadvideo" class="dra-item"><view style="font-size: 20px;color: #dcdcdc;" class="iconfont icon-shiping icon"></view>上传视频</view>
</uni-drawer>

上传方法代码

upLoadImg(){
    const that = this;
    uni.chooseImage({
        sizeType: [\'original\', \'compressed\'], //可以指定是原图还是压缩图,默认二者都有
        sourceType: [\'album\'], //从相册选择
        success: (res)=>{
            console.log(res)
            for(let i=0; i<res.tempFilePaths.length;i++){  //多次调用上传接口,一张一张传  
                uni.uploadFile({
                    url: \'http://127.0.0.1:7001/upload\',//你的接口地址  需修改
                    filePath: res.tempFilePaths[i],//上传返回的文件本地路径 无需修改
                    fileType: \'image\',//文件类型 上传图片的话无需动
                    name: \'file\',  无需修改
                    success: (res) => {
                        that.$refs.drawer.close()//可不写关闭抽屉用
                    },
                    fail: (err) => {
                    }
                });
            }
        }
    })
},
//上传视频,参数与上相同 upLoadvideo(){ const that
= this; uni.chooseVideo({ count: 1, sourceType: [\'camera\', \'album\'], success: function (res) { uni.uploadFile({ url: \'http://127.0.0.1:7001/uploadVideo\', filePath: res.tempFilePath, fileType: \'video\', name: \'file\', success: (res) => { that.$refs.drawer.close() }, fail: (err) => { } }); } }); },

2.后端(egg.js)

router.js

router.post(\'/upload\', controller.alioss.upload);
router.post(\'/uploadVideo\', controller.alioss.uploadVideo);

controller

\'use strict\';

const Controller = require(\'egg\').Controller;
const fs = require(\'mz/fs\');
const OSS = require(\'ali-oss\'); //需要安装 npm install ali-oss -D
const random = require(\'string-random\'); //生成随机字符拼接在下方文件名前,防止上传相同名字文件前者被覆盖(需安装) npm install string-random -D

const aliInfo = {
  region: \'oss-cn-beijing\', 需配置(我的是beijing,按照oss-cn-xxxxx格式填)
  bucket: \'hllspace\',//oss中bucket名字 需配置
  accessKeyId: \'xxxxxx\',//阿里云里面获得
  accessKeySecret: \'xxxxxxxx\',//阿里云里面获得
  endpoint: \'oss-cn-beijing.aliyuncs.com\',//地域节点,阿里云中获得
};

const client = new OSS(aliInfo);

class AliOssController extends Controller {
  async upload() {
    const { ctx } = this;
    const file = ctx.request.files[0];//获取前端传来的文件
    let result;
    let img;
    try {
      result = await client.put(`picture/${random(8) + file.filename}`, file.filepath); //上传文件到oss,第一个参数为文件存放地址+文件名,第二个是文件路径 详细见(https://help.aliyun.com/document_detail/111265.html?spm=a2c4g.11186623.6.1382.29157916dwptKL
      img = await ctx.model.Picture.create({ //将oss返回的图片服务器地址存到视频表中
        imgUrl: result.url,
      });
    } finally {
      // 需要删除临时文件
      await fs.unlink(file.filepath);
    }
    ctx.body = {
      result,
      img,
      state: \'success\',
      msg: \'新增成功\',
    };
  }

//上传视频,参数与上相同 async uploadVideo() { const { ctx }
= this; const file = ctx.request.files[0]; console.log(file); let result; let video; try { // 处理文件,比如上传到云端 result = await client.put(`video/${random(8) + file.filename}`, file.filepath); video = await ctx.model.Video.create({ videoUrl: result.url, }); } finally { // 需要删除临时文件 await fs.unlink(file.filepath); } ctx.body = { result, video, state: \'success\', msg: \'新增成功\', }; } } module.exports = AliOssController;

config.default.js(配置文件类型)

 config.multipart = {
    mode: \'file\',
    fileSize: \'50mb\', // 接收文件大小
    whitelist: [ // 允许接收的文件类型
      \'.png\',
      \'.jpg\',
      \'.mp4\',
    ],
  };

博客如有帮助,那就给个赞吧!有问题评论,看到就回复。