首先需要创建一个express工程:express /temp/upload&& cd /temp/upload
然后安装组件: npm install -d
打开index.jade文件构建一个输出给用户的页面:
html
head
meta(http-equiv='Content-Type', content='text/html',charset='UTF-8')
body
form(action='/showImage/imageFile',enctype='multipart/form-data' ,method='post')
input(type='text',name='username',id='fileInformation')
input( type='file', name='upload',id='imageFile',multiple='multiple')
input( type='submit', value='上传')
在app.js中配置路由并且设置如何处理post上来的数据:
app.get('/showImage',routes.showImage);
//使用标准的redirect after post 模式
app.post('/showImage/:id', function (req, res) {
var id = req.params.id;
console.log("the id is:"+id);
// console.log(req.files.upload);
var tmp_path = req.files.upload.path;
fs.renameSync(tmp_path,"/tmp/test.png");//采用同步的方式把图片放到缓存
if(id=="imageFile")
{
console.log(" the image is exist!");
res.redirect('http://localhost:3000/showImage');
}
else{
res.send("the request is not exist!");
res.end();
}
});
然后在index.js中添加一个接口模块:
exports.showImage = function(req, res){
// res.render('showImage');
fs.readFile("/tmp/test.png", "binary", function(err, file) {//读取缓存
res.writeHead(200, {"Content-Type": "image/png"});
res.write(file, "binary");//采用二进制的方式输出到页面
// fs.unlink("/tmp/test.png");
res.end();
});
};
//使用先把文件存储再显示的模式(需要自己写一个file-upload页面jade文件,注意改一下inde.jade中form表单的action改为'/file-upload')
app.post('/file-upload', function(req, res, next) {
console.log(req.body);
console.log(req.files);
var tmp_path = req.files.upload.path; // 获得文件的临时路径
var target_path = './public/images/' + req.files.upload.name;// 指定文件上传后的目录
fs.rename(tmp_path, target_path, function(err) { // 移动文件
if (err) throw err;
fs.unlink(tmp_path, function() {// 删除临时文件夹文件,
if (err) throw err;
var uploadImageSize=req.files.upload.size;
var uploadImageName=req.files.upload.name;
res.render("file-upload",{imagePath:target_path,imageSize:uploadImageSize,imageName:uploadImageName});
res.end();
}
)
});
});
file-upload.jade:
html
head
meta(http-equiv='Content-Type', content='text/html', charset='UTF-8')
body
p 上传文件目录:#{imagePath}
p 上传文件大小:#{imageSize}bytes
img(src='images/#{imageName}',alt='images')