js数据保存在服务器文件夹内,阿里开源框架egg.js接收存储图片,并保存到数据库中(一)...

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

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值