uniapp 上傳圖片,視頻,文件 到阿里雲oss (egg.js后端)


直接上代碼:(博客中紅色標注請注意)

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',
    ],
  };

博客如有幫助,那就給個贊吧!有問題評論,看到就回復。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM