From a0ca0620efb6e164816a6f32c897ade69af43bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=87=E5=A4=A9?= Date: Mon, 21 Sep 2020 16:22:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0sendfile;=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +++ Readme.md | 14 ++++++++++---- index.js | 22 ++++++++++++++++++++-- package.json | 13 ++++++------- 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index 7c24ca8..351c0c3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ ._* .idea .vscode + + +node_modules/ \ No newline at end of file diff --git a/Readme.md b/Readme.md index 81b8b6e..037ee6f 100644 --- a/Readme.md +++ b/Readme.md @@ -144,16 +144,22 @@ response.render(txt) response.render("You're not able to here", 401) ``` -### sendfile(data, filename) +### sendfile(target, name) -* data `` | `` -* filename `` +* target `` | `` 可以是文件路径, 可以是文本, 可以是Buffer +* name `` 要保存的文件名 > 直接以附件形式响应, 作为文件下载功能. ```javascript +// 不推荐 let pic = fs.readFileSync('./boy.jpg') -response.sendfile(pic, 'a-little-boy.jpg') // +response.sendfile(pic, 'a-little-boy.jpg') + +// 推荐使用 +response.sendfile('./boy.jpg', 'a-little-boy.jpg') + +response.sendfile('blablabla', 'bb.txt') ``` diff --git a/index.js b/index.js index e03114c..52d42f1 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ * @date 2020/09/16 14:52:58 */ +import fs from 'iofs' import STATUS_TEXT from './lib/http-code.js' export default class Response { @@ -105,14 +106,31 @@ export default class Response { } // 文件下载 - sendfile(data, filename) { + sendfile(target, filename) { if (this.rendered) { return } + var data + this.set('Content-Type', 'application/force-download') this.set('Accept-Ranges', 'bytes') - this.set('Content-Length', Buffer.byteLength(data)) this.set('Content-Disposition', `attachment;filename="${filename}"`) + + if (Buffer.isBuffer(target)) { + data = target + } else { + if (typeof target === 'string') { + var stat = fs.stat(target) + if (stat.isFile()) { + this.set('Content-Length', stat.size) + fs.origin.createReadStream(target).pipe(this.origin.res) + return + } + } + data = Buffer.from(target + '') + } + + this.set('Content-Length', data.length) this.end(data) } diff --git a/package.json b/package.json index 72e3eed..9fbf776 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,14 @@ { "name": "@gm5/response", - "version": "1.1.0", + "version": "1.2.0", "type": "module", "description": "对Http的response进一步封装, 提供常用的API", "main": "index.js", "author": "yutent", - "keywords": [ - "fivejs", - "response", - "http" - ], - "repository": "https://github.com/bytedo/gm5.response.git", + "keywords": ["fivejs", "response", "http"], + "dependencies": { + "iofs": "^1.5.0" + }, + "repository": "https://github.com/bytedo/gmf.response.git", "license": "MIT" }