koa文件上传(详解koa-body)

koa-body

const koa = require('koa')
const koaBody = require('koa-body')
const path = require('path')
const app = new koa()
let app = new Koa();
app.use(koaBody({
      // 支持文件格式
      multipart: true,
      formidable: {
          // 上传目录
          uploadDir: path.join(__dirname, './static'),
          // 保留文件扩展名
          keepExtensions: true,
      }
}))
let r1 = router()
app.use(r1.routes());


r1.post('/file', async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    const file = ctx.request.files.file
    ctx.body = { path: file.path }

})

前端,target是让页面表单提交不刷新页面主页有讲过不刷新页面的几种方法

	<form action="http://127.0.0.1:301/file"  
	method="post" 
	enctype="multipart/form-data" target="hidden">

我们打印file看看都有哪些东西

    console.log(file)
File{  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 96938,
  path:
   'C:\\Users\\lx997\\Desktop\\v1.2\\plaformServer\\static\\upload_556a3f67a68a1fa91e2a447513780ba3.jpg',
  name: '微信图片_20200213181546.jpg',
  type: 'image/jpeg',
  hash: null,
  lastModifiedDate: 2020-03-13T03:10:15.545Z,
  _writeStream:
   WriteStream {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: true,
        needDrain: true,
        ending: true,
        ended: true,
        finished: true,
        destroyed: true,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false,
        emitClose: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: false,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     path:
      'C:\\Users\\lx997\\Desktop\\v1.2\\plaformServer\\static\\upload_556a3f67a68a1fa91e2a447513780ba3.jpg',
     fd: null,
     flags: 'w',
     mode: 438,
     start: undefined,
     autoClose: true,
     pos: undefined,
     bytesWritten: 96938,
     closed: false } 

不难发现我们上传的图片默认图片名字被加密定义,为了避免文件名重复我们可以继续使用它们自定义名称,但是怎么把图片通过地址传给前端
在这里插入图片描述
koa-static

//path.basename
var path= require("path");
path.basename('/foo/bar/baz/asdf/quux.html') 
// returns 
'quux.html' 
const koaStatic = require('koa-static')

app.use(koaStatic(path.join(__dirname, 'static')))
//ctx.origin 拿到服务器的域名

r1.post('/file', async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    const file = ctx.request.files.file
    ctx.body = { path: file.path }
    console.log(file)


    const basename = path.basename(file.path)
    ctx.body = { "url": `${ctx.origin}/static/${basename}` }
    let a = {"url": `${ctx.origin}/static/${basename}` }
    console.log(basename)
    console.log(a)
})

都能够正常打印但是我们发现访问图片找不到
在这里插入图片描述
仔细观法发现static被解析了两次这样的文件路径是static/static/图片地址
解决方法很简单随便删一处即可,成功
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值