Vue 구성 요소 가 그림 과 동 영상 을 업로드 하 는 예제 코드 를 패키지 합 니 다.
  우선 다운로드 의존:
cnpm i -S vue-uuid ali-oss
그림 과 비디오 필드 는 여러 파일 을 업로드 할 수 있 도록 배열 형식 입 니 다.
UploadImageVideo:
<!--UploadImageVideo         -->
<template>
  <div class="UploadImageVideo">
    <el-upload
      action
      :on-change="handleChange"
      :on-remove="handleRemove"
      :limit="limitFileNumber"
      :on-exceed="handleExceed"
      :file-list="_fileList"
      :http-request="handleHttpRequest"
      :before-upload="handleBeforeUpload"
      :multiple="isMultiple"
    >
      <el-button slot="trigger" size="small" type="primary">    </el-button>
      <div slot="tip" class="el-upload__tip">{{ tip }}</div>
    </el-upload>
 
    <el-dialog
      title="    "
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <el-progress :text-inside="true" :stroke-width="26" :percentage="percentage"></el-progress>
    </el-dialog>
  </div>
</template>
 
<script>
import { uuid } from "vue-uuid";
const OSS = require("ali-oss");
 
export default {
  name: "",
  components: {},
  props: {
    region: {
      type: String,
      default: "oss-cn-chengdu"
    },
    accessKeyId: {
      type: String,
      default: "xxx"
    },
    accessKeySecret: {
      type: String,
      default: "xxx"
    },
    //    
    bucket: {
      type: String,
      required: true
    },
    currentUrls: {
      type: Array,
      default: () => [],
      required: true
    },
    //        
    limitFileNumber: {
      type: Number,
      default: 1
    },
    //      
    isMultiple: {
      type: Boolean,
      default: false
    },
    //    
    fileType: {
      type: String,
      default: ""
    },
    //  
    tip: {
      type: String
    }
  },
  data() {
    return {
      client: new OSS({
        region: this.region,
        accessKeyId: this.accessKeyId,
        accessKeySecret: this.accessKeySecret,
        bucket: this.bucket
      }),
      percentage: 0,
      dialogTableVisible: false,
      fileList: []
    };
  },
  computed: {
    //  :        console.log()   ,                             !!!!!!
    _fileList() {
      const arr = [];
      //   this.currentUrls        ,     
      if (this.currentUrls.length !== 0) {
        for (const item of this.currentUrls) {
          let { pathname } = new URL(item);
          arr.push({ name: decodeURIComponent(pathname), url: item });
        }
      }
 
      this.fileList = arr; //       !!
      return arr;
    }
  },
  created() {},
  mounted() {},
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `       ${this.limitFileNumber}    ,      ${
          files.length
        }    ,     ${files.length + fileList.length}    `
      );
    },
 
    //  :        handleHttpRequest  ,   :
    // 1、  :auto-upload='true'        ,      true  2、  action='#'     action
    handleHttpRequest(file) {
      //      ,         !
    },
    //  :     handleHttpRequest     ,    before-upload    
    handleBeforeUpload(file) {
      if (this.fileType == "image") {
        let { type, size, name } = file;
        let isJPEG = type === "image/jpeg";
        let isJPG = type === "image/jpg";
        let isPNG = type === "image/png";
        let isLt5M = size / 1024 / 1024 < 5;
        if (!isJPEG && !isJPG && !isPNG) {
          this.$message.error("        JPEG/JPG/PNG    !");
          return false;
        }
        if (!isLt5M) {
          this.$message.error("           5MB!");
          return false;
        }
      }
      if (this.fileType == "video") {
        let { type, size, name } = file;
        let isMP4 = type === "video/mp4";
        let isLt50M = size / 1024 / 1024 < 50;
        if (!isMP4) {
          this.$message.error("        MP4    !");
          return false;
        }
        if (!isLt50M) {
          this.$message.error("           50MB!");
          return false;
        }
      }
    },
    //       ,      。          alioss,        url   。        
    async UploadImageVideo(filename, file) {
      let newFileName =
        filename.split(".")[0] + "-" + uuid.v1() + "." + filename.split(".")[1];
      let that = this;
      that.dialogTableVisible = true;
 
      let {
        res: { requestUrls }
      } = await this.client.multipartUpload(newFileName, file, {
        progress: function(p, checkpoint) {
          that.percentage = parseFloat((p * 100).toFixed(2));
        }
      });
      if (that.percentage == 100) {
        that.dialogTableVisible = false;
      }
      let { origin, pathname } = new URL(requestUrls[0]);
      return origin + decodeURIComponent(pathname);
    },
    //      。       url  
    async addFiles() {
      let urls = [];
      if (this.fileList.length !== 0) {
        for (const item of this.fileList) {
          let { name, raw } = item;
          let pathname = await this.UploadImageVideo(name, raw);
          urls.push(pathname);
        }
      }
      return urls;
    },
    //      。         ,           ,      url  
    async UpdateFiles() {
      let arr_newUploaded = []; //      url。
      let arr_original = []; //     url。    
      let arr_delete = []; //       url。
      if (this.fileList.length !== 0) {
        for (const { raw, name, url } of this.fileList) {
          //  :       raw    。  ,        ;   ,       
          if (raw) {
            let pathname = await this.UploadImageVideo(name, raw);
            arr_newUploaded.push(pathname);
          }
          if (this.currentUrls.includes(url)) {
            arr_original.push(url);
          }
        }
      }
 
      for (const element of this.currentUrls) {
        if (!arr_original.includes(element)) {
          arr_delete.push(element);
        }
      }
      await this.deleteMultiFiles(arr_delete);
 
      return [...arr_original, ...arr_newUploaded];
    },
    //           。  :         url  。
    async deleteMultiFiles(urls = []) {
      let arr_pathname = [];
      if (urls.length !== 0) {
        for (const item of urls) {
          //   let url=require("url");url.parse();   。  new URL()
          let { pathname } = new URL(item);
          // decodeURIComponent()           
          arr_pathname.push(decodeURIComponent(pathname));
        }
        //         
        await this.client.deleteMulti(arr_pathname);
      }
    }
  },
  watch: {}
};
</script>
 
<style lang="scss" scoped>
.UploadImageVideo {
  /*  upload      */
  ::v-deep .el-upload-list__item {
    transition: none !important;
  }
}
</style>사용:
<UploadImageVideo
  ref="ref_UploadImageVideo"
  bucket="xxx"
  :currentUrls="formData.imgurl"
  :limitFileNumber="3"
  tip="1、    3   ; 2、        JPEG/JPG/PNG   ; 3、           5MB!"
  fileType="image"
  :isMultiple="true"
></UploadImageVideo>예 1:
  
   
  
<!--userManage-->
<template>
  <div class="userManage">
    <el-card>
      <div style="margin-bottom: 10px">
        <el-input
          v-model="searchName"
          clearable
          placeholder="        "
          style="width: 200px; margin-right: 10px"
        />
        <el-button
          sizi="mini"
          type="success"
          icon="el-icon-search"
          @click="searchUser(searchName)"
        >  </el-button>
        <el-button
          sizi="mini"
          type="warning"
          icon="el-icon-refresh-left"
          @click="searchName = ''"
        >  </el-button>
        <el-button sizi="mini" @click="handleAdd()" type="primary" icon="el-icon-plus">  </el-button>
        <el-button @click="getUserList()" sizi="mini" icon="el-icon-refresh" style="float: right">  </el-button>
      </div>
      <el-table :data="tableData" border v-loading="isLoading">
        <el-table-column label="   " prop="username" align="center" width="150px"></el-table-column>
        <el-table-column label="  " prop="password" align="center"></el-table-column>
        <el-table-column label="  " align="center">
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                justify-content: space-around;
                flex-flow: row wrap;
              "
            >
              <el-image
                style="width: 50px; height: 50px"
                v-for="(item, index) in scope.row.imgurl"
                :key="index"
                :src="item"
                :preview-src-list="scope.row.imgurl"
              ></el-image>
              <!-- <a :href="scope.row.imgurl" rel="external nofollow"  target="_blank">{{scope.row.imgurl}}</a> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="  " align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="showEditDialog(scope.row)">
              <i class="el-icon-edit" />   
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              <i class="el-icon-delete" />   
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <UserManageDialog :dialog="dialog" :formData="formData" @addUser="addUser" @editUser="editUser"></UserManageDialog>
  </div>
</template>
 
<script>
import UserManageDialog from "./userManageDialog.vue";
import { client_alioss, deleteMultiFiles } from "@/utils/alioss.js";
 
import {
  addUser,
  getUserList,
  editUser,
  deleteUser,
  searchUser
} from "@/api/userManage/index";
export default {
  name: "userManage",
  components: { UserManageDialog },
  data() {
    return {
      searchName: "",
      isLoading: false,
      dialog: {
        show: false,
        title: ""
      },
      formData: {},
      tableData: [
        {
          _id: "",
          username: "admin",
          password: "123",
          imgurl: []
        }
      ],
      currentImgs: []
    };
  },
  props: {},
  created() {},
  mounted() {
    this.getUserList();
  },
  computed: {},
  methods: {
    //      
    async getUserList() {
      this.isLoading = true;
      let { data } = await getUserList();
      this.tableData = data.data;
      this.isLoading = false;
    },
 
    //        
    handleAdd() {
      this.dialog = {
        show: true,
        title: "    ",
        option: "add"
      };
      this.formData = {
        username: "",
        password: "",
        imgurl: []
      };
    },
    //        
    showEditDialog(row) {
      this.currentImgs = row.imgurl;
 
      this.dialog = {
        show: true,
        title: "    ",
        option: "edit"
      };
      this.formData = {
        _id: row._id,
        username: row.username,
        password: row.password,
        imgurl: row.imgurl
      };
    },
    //    
    async addUser(urls) {
      this.formData.imgurl = urls;
 
      await addUser(this.formData);
      this.dialog.show = false;
      this.$notify({
        title: "  ",
        message: "      !",
        type: "success"
      });
      this.getUserList();
    },
    //    
    async editUser(urls) {
      this.formData.imgurl = urls;
 
      await editUser(this.formData, this.formData._id); //     ,     url
 
      this.dialog.show = false;
      this.$notify({
        title: "  ",
        message: "      !",
        type: "success"
      });
      this.getUserList();
    },
    //    
    handleDelete({ _id }) {
      this.$confirm("           ,     ?", "  ", {
        confirmButtonText: "  ",
        cancelButtonText: "  ",
        type: "warning"
      })
        .then(async () => {
          this.$message({
            type: "success",
            message: "    !",
            showClose: true
          });
          let {
            data: { imgurl }
          } = await deleteUser(_id);
 
          //         。      url  
          await deleteMultiFiles(imgurl);
 
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "     ",
            showClose: true
          });
        });
    },
    //       
    async searchUser(searchName) {
      this.isLoading = true;
      let { data } = await searchUser({
        searchName
      });
      this.tableData = data.data;
      this.isLoading = false;
    }
  },
  watch: {}
};
</script>
 
<style lang="scss" scoped>
.userManage {
}
</style>  
 
<!--userManageDialog   -->
<template>
  <div class="userManageDialog">
    <el-dialog :title="dialog.title" width="45%" :visible.sync="dialog.show" v-if="dialog.show">
      <el-form ref="ref_form_userManage" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="   " prop="username">
          <el-input v-model="formData.username" autocomplete="off" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item label="  " prop="password">
          <el-input v-model="formData.password" autocomplete="off" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item label="  " prop="imgurl">
          <!-- fileType      ,    、      。fileType="image"        。fileType="video"         -->
          <UploadImageVideo
            ref="ref_UploadImageVideo"
            bucket="bucket-lijiang-test"
            :currentUrls="formData.imgurl"
            :limitFileNumber="3"
            tip="1、    3   ; 2、        JPEG/JPG/PNG   ; 3、           5MB!"
            fileType="image"
            :isMultiple="true"
          ></UploadImageVideo>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">   </el-button>
        <el-button
          v-if="dialog.option == 'add'"
          @click="addUser('ref_form_userManage')"
          type="primary"
        >   </el-button>
        <el-button
          v-if="dialog.option == 'edit'"
          @click="editUser('ref_form_userManage')"
          type="primary"
        >   </el-button>
      </div>
    </el-dialog>
  </div>
</template>
 
<script>
import UploadImageVideo from "@/components/UploadImageVideo";
 
export default {
  name: "userManageDialog",
  components: { UploadImageVideo },
  props: ["dialog", "formData"],
  data() {
    return {
      fileList: [],
      rules: {
        username: [
          { required: true, message: "       ", trigger: "blur" }
        ]
      }
    };
  },
  created() {},
  mounted() {},
  computed: {},
  methods: {
    addUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let urls = await this.$refs["ref_UploadImageVideo"].addFiles();
          this.$emit("addUser", urls);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let urls = await this.$refs["ref_UploadImageVideo"].UpdateFiles();
 
          this.$emit("editUser", urls);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  watch: {}
};
</script>
<style lang="scss" scoped>
</style>  
import { uuid } from 'vue-uuid';
const OSS = require("ali-oss");
 
let client = new OSS({
    region: "oss-cn-chengdu",
    accessKeyId: "LTAI5tQPHvixV8aakp1vg8Jr",
    accessKeySecret: "xYyToToPe8UFQMdt4hpTUS4PNxzl9S",
    bucket: "bucket-lijiang-test",
 
});
 
export const client_alioss = client;
 
 
//      
export async function deleteMultiFiles(urls = []) {
    let arr_pathname = [];
    if (urls.length !== 0) {
        for (const item of urls) {
            //   let url=require("url");url.parse();   。  new URL()
            let { pathname } = new URL(item);
            // decodeURIComponent()           
            arr_pathname.push(decodeURIComponent(pathname));
        }
        await client.deleteMulti(arr_pathname);
    }
}  
 
import request from '@/utils/request'
//        
export function getUserList() {
    return request({
        url: '/api/userManage',
        method: 'get'
    })
}
 
//      
export function addUser(data) {
    return request({
        url: '/api/userManage',
        method: 'post',
        data
    })
}
 
//      
export function editUser(data, _id) {
    return request({
        url: `/api/userManage/${_id}`,
        method: 'put',
        data
    })
}
 
//      
export function deleteUser(_id) {
    return request({
        url: `/api/userManage/${_id}`,
        method: 'delete'
    })
}
 
//         
export function searchUser(data) {
    return request({
        url: `/api/userManage/search`,
        method: 'get',
        params: data
    })
}
   
const router = require('koa-router')()
 
const User = require("../models/User"); //      
router.prefix('/userManage')
 
//      
router.get('/', async (ctx, next) => {
    let data = await User.find({})
    ctx.body = {
        code: 200,
        message: "    ",
        data,
    }
})
//    
router.post('/', async (ctx, next) => {
    let { username, password, imgurl } = ctx.request.body;
    await User.create({ username, password, imgurl })
    ctx.body = { code: 200, message: "    " }
})
//    
router.put('/:_id', async (ctx, next) => {
    let { username, password, imgurl } = ctx.request.body;
    let { _id } = ctx.params
 
    await User.findByIdAndUpdate(_id, { username, password, imgurl })
    ctx.body = { code: 200, message: "    " }
})
//    
router.delete('/:_id', async (ctx, next) => {
    let { _id } = ctx.params;
    let { imgurl } = await User.findByIdAndDelete(_id)
    ctx.body = { code: 200, message: "    ", imgurl }
 
})
 
//         。    
 
router.get('/search', async (ctx, next) => {
    let { searchName } = ctx.request.query;
 
    let data = await User.find({ username: { $regex: searchName } })
    ctx.body = { code: 200, message: "    ", data }
})
module.exports = routerVue 패 키 징 에 사진 과 동 영상 을 올 리 는 구성 요소 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 vue 구성 요소 패 키 징 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Fastapi websocket 및 vue 3(Composition API)1부: FastAPI virtualenv 만들기(선택 사항) FastAPI 및 필요한 모든 것을 다음과 같이 설치하십시오. 생성main.py 파일 및 실행 - 브라우저에서 이 링크 열기http://127.0.0.1:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.