鍍金池/ 問答/HTML/ koa2 怎么把public目錄下的圖片返回給前臺

koa2 怎么把public目錄下的圖片返回給前臺

前端使用iview 上傳圖片到koa2的服務(wù)器中。

router.post('/upLoad', upload.single('file'), async(ctx, next) => {
    const filename = `http://localhost:3000/public/images/${ctx.req.file.filename}`
    ctx.body = {
        code: 'success',
        filename: filename
    }
})

這里想要返回一個url地址,可以直接點(diǎn)擊這個url地址就可以看到圖片內(nèi)容。
應(yīng)該怎么來做。

回答
編輯回答
維她命

可以使用koa-sendfile模塊實(shí)現(xiàn),github鏈接
官網(wǎng)的示例也很簡單

var sendfile = require('koa-sendfile')

app.use(function* (next) {
  var stats = yield sendfile(this, '/Users/jong/.bash_profile')
  if (!this.status) this.throw(404)
})
2018年4月6日 17:32
編輯回答
雨萌萌

問題解決了:

這是配置的靜態(tài)文件夾地址
app.use(require('koa-static')(__dirname + '/public'))

在public文件夾下面有imgs文件夾,里面存放了上傳的圖片,
通過url訪問的時候,http://localhost:3000/images/1510641058048.jpeg
不需要填寫public這個路徑了

2017年3月24日 01:54