Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

附件下载 #169

Open
wuxianqiang opened this issue Jun 21, 2019 · 0 comments
Open

附件下载 #169

wuxianqiang opened this issue Jun 21, 2019 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

wuxianqiang commented Jun 21, 2019

在一些场景下,无论响应的内容是什么样的MIME值,需求中并不要求客户端去打开它,只需弹出并下载它即可。为了满足这种需求, Content-Disposition 字段应声登场。 Content-Disposition 字段影响的行为是客户端会根据它的值判断是应该将报文数据当做即时浏览的内容,还是可下载的附件。当内容只需即时查看时,它的值为 inline ,当数据可以存为附件时,它的值为 attachment 。另外, Content-Disposition 字段还能通过参数指定保存时应该使用的文件名。示例如下:

Content-Disposition: attachment; filename="filename.ext"

如果我们要设计一个响应附件下载的API(res.sendfile),我们的方法大致是如下这样的:

const http = require('http')
const url = require('url')
const fs = require('fs')

const server = http.createServer((req, res) => {
  const { pathname } = url.parse(req.url)
  if (pathname === '/') {
    const html = fs.createReadStream('./public/index.html')
    html.pipe(res)
    return
  }
  if (pathname === '/download') {
    fs.stat('./images/th.jpg', function (err, stat) {
      const stream = fs.createReadStream('./images/th.jpg')
      res.writeHead(200, {
        'Content-Type': 'image/jpeg',
        'Content-Length': stat.size,
        'Content-Disposition': 'attachment; filename=th.jpg'
      })
      stream.pipe(res)
    });
    return
  }
  res.end('404')
})

server.listen(8080, () => {
  console.log('port in 8080')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant