本文Demo的完整工程代码, 参考file-upload-server / file-upload-client
目录
服务
express
cnpm i -g express-generator && express -e file-upload-server
cd file-upload-server && cnpm i
npm start
- 测试
curl localhost:3000
touch routes/upload.js
var express = require('express');
var router = express.Router();
// 上传单个文件
router.post('/single', function (req, res, next) {
res.send({ ret_code: '0' });
});
module.exports = router;
- 测试
curl -X POST localhost:3000/upload/single
multer
cnpm i --save multer
mkdir middleware && touch middleware/upload.js
var fs = require('fs');
var multer = require('multer');
// Step 1: 新建upload
var createFolder = function (folder) {
try {
fs.accessSync(folder);
} catch (e) {
fs.mkdirSync(folder);
}
};
var uploadFolder = './upload/';
createFolder(uploadFolder);
// Step 2: 配置multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadFolder);
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
var upload = multer({ storage: storage });
module.exports = upload;
upload
vim routes/upload.js
var express = require('express');
var router = express.Router();
var upload = require('../middleware/upload');
// 上传单个文件
router.post('/single', upload.single('single'), function (req, res, next) {
console.log(req.file);
res.send({ ret_code: '0' });
});
module.exports = router;
echo upload >> .gitignore
vim views/index.ejs
<form action="/upload/single" method="post" enctype="multipart/form-data">
<h2>上传单个文件</h2>
<input type="file" name="single">
<input type="submit" value="提交">
</form>
- 测试
浏览器打开localhost:3000
前端
vue
vue init webpack file-upload-client
cd file-upload-client && cnpm i
npm start
Element
cnpm i --save element-ui
vim src/main.js
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-default/index.css';
import App from './App';
import router from './router';
Vue.use(ElementUI);
Vue.config.productionTip = false;
upload
vim src/components/Hello.vue
<template>
<el-upload action="http://localhost:3000/upload/single" name="single" :on-success="handleSuccess" :on-error="handleError" list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</template>
<script>
export default {
name: 'hello',
methods: {
handleSuccess() {
this.$message.success('上传成功');
},
handleError(err) {
this.$message.error(`上传失败: ${err}`);
},
},
};
</script>
跨域
cd file-upload-server && cnpm i --save cors
vim app.js
var cors = require('cors');
app.use(cors());
筛选
服务
vim middleware/upload.js
// Step 2: 配置multer
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadFolder);
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
var upload = multer({
storage: storage,
limits: { fileSize: 2 * 1000 },
fileFilter: function (req, file, cb) {
if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpeg') {
return cb(new Error('error'));
}
cb(null, true);
}
});
module.exports = upload;
vim ./routes/upload.js
var singleUpload = upload.single('single');
// 上传单个文件
router.post('/single', function (req, res, next) {
singleUpload(req, res, function (err) {
if (err) {
return res.status(500).send({ message: '只能上传jpg/png文件 且不超过2kb' });
}
console.log(req.file);
res.send({ ret_code: '0' });
});
});
module.exports = router;
前端
vim src/components/Hello.vue
<template>
<el-upload action="http://localhost:3000/upload/single" name="single" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件 且不超过2kb</div>
</el-upload>
</template>
<script>
export default {
name: 'hello',
methods: {
beforeUpload(file) {
const isImage = (file.type === 'image/jpeg' || file.type === 'image/png');
const isLt2K = file.size / 1024 < 2;
if (!isImage) {
this.$message.error('上传头像图片只能是jpg/png格式!');
}
if (!isLt2K) {
this.$message.error('上传头像图片大小不能超过2kb!');
}
return isImage && isLt2K;
},
handleSuccess() {
this.$message.success('上传成功');
},
handleError(err) {
this.$message.error(`上传失败: ${err}`);
},
},
};
</script>
待完善
多文件
详细参考node-tutorial中的FileUploadClient&FileUploadServer
数据库
静态资源域名
详细参考前端必知必会的部署知识