切片上传
<body>
<input type="file" id="input">
<button id="btn">上传</button>
<script>
const btn = document.getElementById('btn');
const input = document.getElementById('input');
const chunkSize = 1024;
let index = 0;
btn.addEventListener('click', upload);
function upload() {
const file = input.files[0];
const [filename, ext] = file.name.split('.')
console.log(file);
let start = index * chunkSize;
if (start > file.size) return;
const blob = file.slice(start, start + chunkSize);
const blobName = `${filename}${index}.${ext}`
const blobFile = new File([blob], blobName)
const formData = new FormData();
formData.append('file', blobFile)
fetch('/upload', {
method: 'post',
body: formData
}).then(() => {
index++;
upload()
})
}
</script>
</body>
const Koa = require('koa');
const Router = require('koa-router');
const server = require('koa-static');
const multiparty = require('multiparty');
const path = require('path');
const fs = require('fs');
const app = new Koa();
const router = new Router();
router.post('/upload', async(ctx) => {
var form = new multiparty.Form({
uploadDir: 'temp'
})
form.parse(ctx.req);
form.on('file', (name, file) => {
const newPath = path.resolve(__dirname, 'temp', file.originalFilename)
fs.rename(file.path, newPath, (err) => {
if (err) console.log(err);
})
console.log('上传成功');
})
ctx.response.body = '请求成功';
})
app.use(router.routes());
app.use(server(path.join(__dirname, '/public')));
app.listen(3000, () => {
console.log('server listen at port 3000');
})