如何上傳圖片到七牛雲

下面介紹Element-ui中Upload組件如何把圖片上傳的七牛雲(免費版本,有流量限制)前端

1、準備工做node

1.去七牛雲註冊帳號,並實名認證,不認證沒法建立存儲空間ajax

 

 

 

2.瞭解Element-ui組件express

2、建立上傳頁面(這裏直接使用官方的代碼片斷)後端

<template>
  <div class="editor">
    <h3>上傳圖片</h3>
    <el-form label-width="70px" @submit.native.prevent="save">
      <el-form-item label="圖標">
        <el-upload
          class="avatar-uploader"
          :action="qiniuDomain"
          :http-request="upLoadToQiniu"
          :show-file-list="false"
          :before-upload="beforeUpload"
        >
          <img v-if="model.icon" :src="model.icon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
   // 實名認證後建立的存儲空間對應的上傳地址(華東,華南等等不同:https://developer.qiniu.com/kodo/manual/1671/region-endpoint) qiniuDomain:
"https://upload-z2.qiniup.com",
   // 建立成功後官方隨機分配的公開圖片地址前綴,即上傳成功後對應的公用圖片地址前綴 qiniuViewHost:
"http://q0sm6ce42.bkt.clouddn.com", model: { name: "", icon: "" } }; }, methods: { async upLoadToQiniu(req) { const config = { headers: { "Content-Type": "multipart/form-data" } }; let fileType = ""; if (req.file.type === "image/png") { fileType = "png"; } else { fileType = "jpg"; } // 重命名要上傳的文件 const keyname = `${new Date().getTime()}${Math.random().toString(36).slice(2)}.${fileType}`; // 上傳時候的Token,可前端本身生成,安全起見後端生成!
    // 這裏是express後端生成的Token const res = await this.$http.get("/token"); const token = res.data.uploadToken; const formdata = new FormData(); formdata.append("file", req.file); formdata.append("token", token); formdata.append("key", keyname); const result = await this.$http.post(this.qiniuDomain, formdata, config); this.model.icon = `${this.qiniuViewHost}/${result.data.key}`; }, beforeUpload(file) { // debugger const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt10M = file.size / 1024 / 1024 < 10; if (!isJPG) { this.$message({ showClose: true, message: "上傳圖片只能是JPG/PNG 格式!", type: "error" }); } if (!isLt10M) { this.$message({ showClose: true, message: "上傳頭像圖片大小不能超過 10MB!", type: "error" }); } return isJPG && isLt10M; }, }, created() { // 其餘ajax } }; </script>

 

3、上傳憑證(Token)如何得到:https://developer.qiniu.com/kodo/manual/1208/upload-tokenapi

// 七牛雲官方node.js CDK
const qiniu = require('qiniu');

const config = {
  // 我的中心->祕鑰管理->AccessKey
  "AK": "xxxxxx你本身的",
  // 我的中心->祕鑰管理->SecretKey
  "SK": "xxxxxx你本身的",
  // 對象存儲->新建存儲空間的名字:(你本身建立時候空間名字),這裏我建立的是:jiuchengjsfront
  "Bucket": "jiuchengjsfront"
}
  // 這裏是根據express定義的接口返回給客戶端的:token
  app.get('/admin/api/token', async(req, res)=> {
    const mac = new qiniu.auth.digest.Mac(config.AK, config.SK);
    const options = {
        scope: config.Bucket,
        expires: 3600 * 24
    };
    const putPolicy =  new qiniu.rs.PutPolicy(options);
    const uploadToken= putPolicy.uploadToken(mac);
    res.send({
      uploadToken
    })
  })

也能夠不從接口獲取,本身定義成功的方法。安全起見別暴露給別人安全

// 七牛雲官方node.js CDK
const qiniu = require('qiniu');

const config = {
  // 我的中心->祕鑰管理->AccessKey
  "AK": "你本身的Accesskey",
  // 我的中心->祕鑰管理->SecretKey
  "SK": "你本身的Secretkey",
  // 對象存儲->新建存儲空間的名字:(你本身建立時候空間名字)
  "Bucket": "jiuchengjsfront"
}
// 官方文檔:https://developer.qiniu.com/kodo/manual/1208/upload-token
const mac = new qiniu.auth.digest.Mac(config.AK, config.SK);
const options = {
  scope: config.Bucket,
  expires: 3600 * 24
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);

export default uploadToken

// 使用的時候替換爲
 formdata.append("token", uploadToken);
const result = await this.$http.post(this.qiniuDomain, formdata, config);
this.model.icon = `${this.qiniuViewHost}/${result.data.key}`;

4、上傳成功以後如:app

 

 

相關文章
相關標籤/搜索