文件上传
采用百度团队开发的webuploader + express部署服务器。
文件上传
1、服务器搭建
var fs = require('fs');
var express = require('express');
var bodyParder = require('body-parser');
var multer = require('multer');
var app = express();//初始化app
app.use(bodyParder());
app.use(express.static(__dirname + ''));
app.all('*',function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
if(req.method=="OPTIONS") res.send(200);//让options请求快速返回
else next();
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/'); // 保存的路径,备注:需要自己创建
},
filename: function (req, file, cb) {
// 将保存文件名设置为 字段名 + 时间戳,比如 logo-1478521468943
var fileformat = (file.originalname).split('.');
cb(null, file.fieldname + '-' + Date.now()+'.'+fileformat[fileformat.length-1]);
}
});
var upload = multer({ storage: storage })
// var upload = multer({ dest: 'uploads/' })
app.get('/file', function(req, res){
res.send('download file');
});
app.post('/file', upload.single('file'), function (req, res, next) {
var file = req.file;
console.log(file.path);
res.send('saved file');
});
app.listen(8000,function(){
console.log('listen on port 8000');
});
2、使用webuploader
//初始化Web Uploader
var uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: true,
// swf文件路径
// swf:'/js/Uploader.swf',
// 文件接收服务端。
server: 'http://localhost:8000/file',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: {
id:'#filePicker',
},
// 只允许选择图片文件。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/jpg,image/jpeg,image/png'
}
});
uploader.on(('uploadFinished'),function(){
console.log('ok!');
}
);
3、遇到的问题
1 增加 accept 字段 导致chorme浏览器反应慢
需要把
accept: {
title: ‘Images’,
extensions: ‘gif,jpg,jpeg,bmp,png’,
mimeTypes: ‘image/*’
}
改为以下:
accept: {
title: ‘Images’,
extensions: ‘gif,jpg,jpeg,bmp,png’,
mimeTypes: ‘image/jpg,image/jpeg,image/png’
}
3.2 设置display:none导致上传按钮点击无效
踩的坑有点多呀,解决办法是不使用displaynone,改为visibility hidden。