koa 文件下载 pdf预览 两个接口 – nodejs – chromeDownload chromePreview

chrome.js

  1. const router = require("koa-router")()
  2. const mime = require('mime-types') //需npm安装
  3. const fs = require('fs')
  4. router.prefix("/chrome")
  5. router.get("/", async (ctx, next) => {
  6. ctx.body = {
  7. title: "/api/chrome/",
  8. }
  9. })
  10. // http://127.0.0.1:31188/api/chrome/chromePreview?E:\root\Personal\English\杨亮英语\【完结】有道词典高考词汇3500\pdf\02.pdf
  11. // http://127.0.0.1:31188/api/chrome/chromePreview?C:\Users\Reciter\Desktop\桌面Fake垃圾桶\1.jpg
  12. router.get('/chromePreview', async (ctx, next) => {
  13. // console.info('ctx.request.query', ctx.request.query)
  14. // let filePath = ctx.request.query.filePath
  15. let filePath = Object.keys(ctx.request.query)[0]
  16. let file = fs.readFileSync(filePath)
  17. let mimeType = mime.lookup(filePath) //读取图片文件类型
  18. ctx.set('content-type', mimeType) //设置返回类型
  19. ctx.body = file //返回图片
  20. })
  21. // http://127.0.0.1:31188/api/chrome/chromeDownload?filePath=E:\root\Personal\English\杨亮英语\【完结】有道词典高考词汇3500\pdf\02.pdf
  22. // http://127.0.0.1:31188/api/chrome/chromeDownload?filePath=C:\Users\Reciter\Desktop\桌面Fake垃圾桶\1.jpg
  23. router.get('/chromeDownload', async (ctx, next) => {
  24. let filePath = ctx.request.query.filePath
  25. console.info('filePath', filePath)
  26. let file = fs.readFileSync(filePath)
  27. let fileName = filePath.split('\\').pop()
  28. ctx.set('Content-disposition', 'attachment;filename=' + encodeURIComponent(fileName))
  29. ctx.body = file //返回图片
  30. })
  31. module.exports = router