-
Notifications
You must be signed in to change notification settings - Fork 396
11 如何上传文件
孙正华 edited this page Jul 26, 2018
·
2 revisions
可以使用 jQuery-File-Upload 和 jquery-file-upload-middleware 中间件来实现上传功能。
安装 jQuery-File-Upload:
$ npm install --save blueimp-file-upload
页面引用:
https://github.com/eshengsky/iBlog2/blob/master/views/admin/settings.pug#L172-L173
script(type='text/javascript', src='/static/blueimp-file-upload/js/vendor/jquery.ui.widget.js', charset='utf-8')
script(type='text/javascript', src='/static/blueimp-file-upload/js/jquery.fileupload.js', charset='utf-8')
定义 file 控件:
https://github.com/eshengsky/iBlog2/blob/master/views/admin/settings.pug#L47
input.fileupload(type='file', name='file')
ajax 发送请求:
https://github.com/eshengsky/iBlog2/blob/master/public/js/settings.js#L20-L30
$(".fileupload").fileupload({
url: "/admin/uploadimg",
dataType: "text",
done: function (e, data) {
if (data.result) {
var path = '/static/images/' + JSON.parse(data.result).files[0].name;
$(this).prev("img").attr("src", path);
$(this).next(":hidden").val(path);
}
}
});
安装中间件:
$ npm install --save jquery-file-upload-middleware
配置上传参数:
https://github.com/eshengsky/iBlog2/blob/master/routes/admin.js#L15-L19
//上传配置
upload.configure({
uploadDir: path.join(__dirname, '../public/images/'),
uploadUrl: '/images'
});
服务端处理上传请求:
https://github.com/eshengsky/iBlog2/blob/master/routes/admin.js#L399-L402
// 上传图片
router.post('/uploadimg', (req, res, next) => {
upload.fileHandler()(req, res, next);
});