更新sendfile;更新依赖

v1
宇天 2020-09-21 16:22:46 +08:00
parent 86fe5916aa
commit a0ca0620ef
4 changed files with 39 additions and 13 deletions

3
.gitignore vendored
View File

@ -7,3 +7,6 @@
._* ._*
.idea .idea
.vscode .vscode
node_modules/

View File

@ -144,16 +144,22 @@ response.render(txt)
response.render("You're not able to here", 401) response.render("You're not able to here", 401)
``` ```
### sendfile(data, filename) ### sendfile(target, name)
* data `<String>` | `<Buffer>` * target `<String>` | `<Buffer>` 可以是文件路径, 可以是文本, 可以是Buffer
* filename `<String>` * name `<String>` 要保存的文件名
> 直接以附件形式响应, 作为文件下载功能. > 直接以附件形式响应, 作为文件下载功能.
```javascript ```javascript
// 不推荐
let pic = fs.readFileSync('./boy.jpg') 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')
``` ```

View File

@ -3,6 +3,7 @@
* @date 2020/09/16 14:52:58 * @date 2020/09/16 14:52:58
*/ */
import fs from 'iofs'
import STATUS_TEXT from './lib/http-code.js' import STATUS_TEXT from './lib/http-code.js'
export default class Response { export default class Response {
@ -105,14 +106,31 @@ export default class Response {
} }
// 文件下载 // 文件下载
sendfile(data, filename) { sendfile(target, filename) {
if (this.rendered) { if (this.rendered) {
return return
} }
var data
this.set('Content-Type', 'application/force-download') this.set('Content-Type', 'application/force-download')
this.set('Accept-Ranges', 'bytes') this.set('Accept-Ranges', 'bytes')
this.set('Content-Length', Buffer.byteLength(data))
this.set('Content-Disposition', `attachment;filename="${filename}"`) 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) this.end(data)
} }

View File

@ -1,15 +1,14 @@
{ {
"name": "@gm5/response", "name": "@gm5/response",
"version": "1.1.0", "version": "1.2.0",
"type": "module", "type": "module",
"description": "对Http的response进一步封装, 提供常用的API", "description": "对Http的response进一步封装, 提供常用的API",
"main": "index.js", "main": "index.js",
"author": "yutent", "author": "yutent",
"keywords": [ "keywords": ["fivejs", "response", "http"],
"fivejs", "dependencies": {
"response", "iofs": "^1.5.0"
"http" },
], "repository": "https://github.com/bytedo/gmf.response.git",
"repository": "https://github.com/bytedo/gm5.response.git",
"license": "MIT" "license": "MIT"
} }