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

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

chrome.js

const router = require("koa-router")()
const mime = require('mime-types') //需npm安装
const fs = require('fs')

router.prefix("/chrome")

router.get("/", async (ctx, next) => {
  ctx.body = {
    title: "/api/chrome/",
  }
})

// http://127.0.0.1:31188/api/chrome/chromePreview?E:\root\Personal\English\杨亮英语\【完结】有道词典高考词汇3500\pdf\02.pdf
// http://127.0.0.1:31188/api/chrome/chromePreview?C:\Users\Reciter\Desktop\桌面Fake垃圾桶\1.jpg
router.get('/chromePreview', async (ctx, next) => {
  // console.info('ctx.request.query', ctx.request.query)
  // let filePath = ctx.request.query.filePath
  let filePath = Object.keys(ctx.request.query)[0]
  let file = fs.readFileSync(filePath)
  let mimeType = mime.lookup(filePath) //读取图片文件类型
  ctx.set('content-type', mimeType) //设置返回类型
  ctx.body = file //返回图片
})

// http://127.0.0.1:31188/api/chrome/chromeDownload?filePath=E:\root\Personal\English\杨亮英语\【完结】有道词典高考词汇3500\pdf\02.pdf
// http://127.0.0.1:31188/api/chrome/chromeDownload?filePath=C:\Users\Reciter\Desktop\桌面Fake垃圾桶\1.jpg
router.get('/chromeDownload', async (ctx, next) => {
  let filePath = ctx.request.query.filePath
  console.info('filePath', filePath)
  let file = fs.readFileSync(filePath)
  let fileName = filePath.split('\\').pop()
  ctx.set('Content-disposition', 'attachment;filename=' + encodeURIComponent(fileName))
  ctx.body = file //返回图片
})

module.exports = router
posted @ 2022-04-02 17:35  彭成刚  阅读(231)  评论(0编辑  收藏  举报