1、安裝koa-body
2、引入koa-body
const koa = require('koa');
const fs = require('fs');
const koaBody = require('koa-body');
const route = require('koa-route');
let app = new koa();
app.use(koaBody(
{
multipart: true,
formidable: {
maxFileSize: 200*1024*1024
}
}));
3、上傳文件的具體操作
const uploadFile = ctx => { const fileName = ctx.request.body.name; const file = ctx.request.files.file; // 創建可讀流 const render = fs.createReadStream(file.path); let filePath = path.join(config.BASE_PATH, 'upload/',fileName+'.'+file.name.split('.').pop()); const fileDir = path.join(config.BASE_PATH, 'upload/'); if (!fs.existsSync(fileDir)) { fs.mkdirSync(fileDir, err => { console.log(err) console.log('創建失敗') }); } // 創建寫入流 const upStream = fs.createWriteStream(filePath); render.pipe(upStream); ctx.body = '上傳成功' }
4、前端ajax請求代碼
<body>
<div>
<form>
<input type="text" class="filename">
<input type="file" name="file" class="imgPath">
<div class="submitBtn">提交</div>
</form>
</div>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.submitBtn').on('click',() => {
var params = new FormData();
params.append('name',$('.filename').val())
params.append('file',$('.imgPath')[0].files[0])
$.ajax({
data: params,
url: '/uploadFile',
type: 'post',
processData: false,
contentType: false,
success: function(res) {
console.log(res)
}
})
})
})
</script>
</body>
