美文网首页
阿里开源框架egg.js接收存储图片,并保存到数据库中(一)

阿里开源框架egg.js接收存储图片,并保存到数据库中(一)

作者: 温暖柏林的伤 | 来源:发表于2019-03-18 15:05 被阅读0次

    需求:用户上传图片到服务器,服务器接收并存在本地。

    1、安装写入文件插件,写入出错关闭管道插件

    npm i await-stream-ready, stream-wormhole -S

    2、配置访问地址router.js,注意要使用POST请求

    router.post('/upload', controller.home.upload);

    3、编写controller控制器home.js

    'use strict';

    const Controller = require('egg').Controller;

    // 文件存储

    const fs = require('fs');

    const path = require('path');

    const awaitWriteStream = require('await-stream-ready').write;

    const sendToWormhole = require('stream-wormhole');

    class HomeController extends Controller {

      async uploadImg() {

        const ctx = this.ctx;

        const stream = await ctx.getFileStream();

        // 文件名:随机数+时间戳+原文件后缀

        // path.extname(stream.filename).toLocaleLowerCase()为后缀名(.jpg,.png等)

        const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();

        // 图片存放在静态资源public/img文件夹下

        const target = path.join(this.config.baseDir, 'app/public/img', filename);

        // 生成一个文件写入 文件流

        const writeStream = fs.createWriteStream(target);

        try {

            let result = await _that.ctx.service.home.upload(params);

                    // 异步把文件流 写入

                    this.ctx.body = {

                        code: result.code,

                        data: result.data,

                        message: result.msg

                    }

        } catch (err) {

            // 如果出现错误,关闭管道

            await sendToWormhole(stream);

            throw err;

        }

        this.ctx.body = {

          code: 0,

          data: filename,

          msg: ''

        };

        // 前端使用:服务器地址+文件名

        // http://localhost:7001/public/img/filename

      }

    }

    module.exports = HomeController;

    相关文章

      网友评论

          本文标题:阿里开源框架egg.js接收存储图片,并保存到数据库中(一)

          本文链接:https://www.haomeiwen.com/subject/tfeelqtx.html