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/图片地址
解决方法很简单随便删一处即可,成功