node实现文件上传到七牛云

使用七牛云提供的Node.js SDK(https://developer.qiniu.com/kodo/1289/nodejs)实现文件上传

服务端:

1、安装JDK

npm/cnpm install qiniu

or

yarn add qiniu

2、导出七牛云配置文件的Token

// 七牛云配置文件
const qiniu = require('qiniu');

// 创建上传凭证(accessKey 和 secretKey在七牛云个人中心中有,blog 是七牛云创建的空间名称)
const accessKey = 'xxxxxxx'; // ak密钥
const secretKey = 'xxxx'; // sk密钥
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
  scope: 'blog' // 存储空间的名字
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);

module.exports = {
  uploadToken // 导出的是七牛云生成的token
};

3、暴露接口给前端使用

// 前端获取到七牛云返回的token
const express = require('express');
//  定义路由级中间件
const router = express.Router();
const uploadToken = require('./qiniu')

router.get('/getQiniuToken', (req, res) => {
  res.json({
    code: 200,
    data: uploadToken.uploadToken,
    messages: '获取成功'
  });
});

module.exports = router;

4、服务层抛出接口

//1.引入express模块
const express = require('express');
const mongoose = require('mongoose');
const bodyParse = require('body-parser');
const mongoObj = {
  hostName: 'xxx', // 数据库地址
  dataBaseName: 'xxx', // 数据库名称
  username: 'xxx',  // 用户名称
  password: 'xxx'  // 用户密码
};
mongoose
  .connect(`mongodb://${mongoObj.username}:${mongoObj.password}@${mongoObj.hostName}/${mongoObj.dataBaseName}`, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => console.log('数据库连接成功!'))
  .catch((err) => console.log('err', err));

mongoose.set('strictQuery', true);
//创建app对象
const app = express();
app.use(bodyParse.json());
app.use(bodyParse.urlencoded({ extended: true }));

// 定义服务启动接口
app.listen(8098, () => {
  console.log('app 8098');
});

// 引入定义的路由并应用
const qiniuToken = require('./routes/qiniuToken');
app.use('/api', qiniuToken);

注(踩坑记):我这里的MongoDB的数据库,会存在一个时不时就被一些无聊的人黑的问题,所以我加了用户名和密码认证,换了端口号,做了每天备份的操作,所以使用数据库的时候一定要注意这个问题。

前端调用:

1、/api/upload.js

import request from '@/utils/request';

// 获取七牛云token
export function getQiniuToken(params) {
  return request({
    url: '/getQiniuToken',
    method: 'get',
    params
  });
}

// 上传文件
export function uploadFile(data) {
  return request({
    url: import.meta.env.VITE_APP_FILE_UPLOAD_API, // 七牛云上传地址 目前我用的华南地区为(https://upload-z2.qiniup.com)
    method: 'post',
    headers: { 'Content-Type': 'multipart/form-data' },
    data
  });
}

2、页面调用封装接口

<template>
  <div class="upload-box">
    <el-upload class="upload-demo" drag :action="upload.action" :http-request="httpRequestFun" :auto-upload="true" :before-upload="beforeUpload">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
      <template #tip>
        <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import moment from 'moment';
import { getQiniuToken, uploadFile } from '@/api/upload';
import { UploadFilled } from '@element-plus/icons-vue';

const upload = ref({
  action: import.meta.env.VITE_APP_FILE_UPLOAD_API, // 华南地区
  httpRequest: import.meta.env.VITE_APP_FILE_PREVIEW_API // 自定义域名
});

const httpRequestFun = async (req) => {
  const { data } = await getQiniuToken();
  const formData = new FormData();
  const fileName = `daily-photos/${moment(new Date()).format('YYYYMMDD')}/${req.file.name}`; // /代表目录
  formData.append('file', req.file);
  formData.append('token', data); // 获取到的七牛云token
  formData.append('key', fileName);  // 文件名称
  const res = await uploadFile(formData);
  console.log(res);
  console.log(upload.value.httpRequest + '/' + res.data.key); // 预览地址
};
</script>

<style lang="scss" scoped>
.upload-box {
  width: 200px;
  height: 150px;
  margin: 0 auto;
}
</style>

上传成功,查看七牛云存储空间文件:

 

posted @ 2023-06-07 16:21  zaijinyang  阅读(333)  评论(0编辑  收藏  举报