更新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
.vscode
node_modules/

View File

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

View File

@ -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)
}

View File

@ -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"
}