上传服务器文件夹
import multer from 'koa-multer'
const storage = multer.diskStorage({
// 文件保存路径
destination: function(req, file, cb) {
cb(null, path.join(__dirname, '../../static'))
},
// 修改文件名称
filename: function(req, file, cb) {
var fileFormat = (file.originalname).split('.')
cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1])
}
})
router.post('/api/v1/file/*', upload.single('file'), async(ctx, res, next) => {
let filename = ctx.req.file.filename
ctx.response.body = { filename }
}
上传阿里云
const co = require('co')
const OSS = require('ali-oss')
const dateformat = require('dateformat')
const path = require('path')
const client = new OSS({
region: 'oss-cn-',
accessKeyId: 'xxx',
accessKeySecret: xxx',
bucket: 'bucketName'
})
const dateStr = dateformat(new Date(), 'yyyymm')
const uploadDir = `static/img/${dateStr}/`
const uploadDir2 = 'static/'
module.exports = {
config(accessKeyId, accessKeySecret) {
client.options.accessKeyId = accessKeyId
client.options.accessKeySecret = accessKeySecret
},
upload: co.wrap(function* (local, destName, reName = true) {
if (reName) {
const filePrex = dateformat(new Date(), 'ddHHMMssl')
destName = uploadDir + filePrex + path.extname(destName)
} else {
destName = uploadDir2 + destName
}
const result = yield client.put(destName, local)
return yield Promise.resolve(result)
})
}
import koaRouter from 'koa-router'
import multer from 'koa-multer'
import path from 'path'
import fs from 'fs'
import oss from '../controllers/upload'
const storage = multer.diskStorage({
// 文件保存路径
destination: function(req, file, cb) {
cb(null, path.join(__dirname, '../../static'))
},
// 修改文件名称
filename: function(req, file, cb) {
var fileFormat = (file.originalname).split('.')
cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1])
}
})
// 加载配置
var upload = multer({storage: storage})
const router = koaRouter()
router.post('/api/v1/file/*', upload.single('file'), async(ctx, res, next) => {
let filename = ctx.req.file.filename
let localPath = path.join(__dirname, '../../static/' + filename)
console.log(uploadUtil)
oss.upload(localPath, filename).then((val) => {
fs.unlink(path)
if (val.res && val.res.status === 200) {
console.log(val.url)
}
}).catch((res) => {
console.log('---error---')
})
})