目標(biāo)
圖片上傳與展示
formidable的使用
首先安裝formidable
npm install formidable
官方文檔展示
淘寶的formidable鏈接
var formidable = require('formidable'),
http = require('http'),
fs = require('fs'),
util = require('util');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files})); //util.inspect(object,[showHidden],[depth],[colors])是一個將任意對象轉(zhuǎn)換 為字符串的方法
});
return;
}
var content = fs.readFileSync('./post2.html');
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(content);
}).listen(8080,function () {
console.log('start form')
});
- 以下是post2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post2</title>
</head>
<body>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="text" name="title">
<br>
<input type="file" name="upload" multiple="multiple">
<br>
<input type="submit" value="Upload">
</form >
</body>
</html>
這里有用的文件思劳,index.js post2.html,router.js,server.js, uploadHandler.js
- uploadHandler.js
var fs = require('fs');
var querystring = require('querystring');
var formidable = require('formidable'),
util = require('util');
function start(response,postData) { //上傳文件頁面
console.log('do post start');
var body = fs.readFileSync('./post2.html');
response.writeHead(200,{"Content-Type":"text/html;charset:utf-8"});
response.write(body);
response.end();
}
function upload(response,request) {
console.log('do upload');
var form = new formidable.IncomingForm();
form.uploadDir = 'public/upload'; //新建一個默認(rèn)存放圖片的目錄圖片傳到這里
form.parse(request,function (err,fields,files) {
response.writeHead(200, {'content-type': 'text/html'});
fs.renameSync(files.upload.path,"temp/test.png"); //修改文件path名
response.write('received image:<br/>');
response.write('![](/show)')
response.end()
})
}
function show(response) { //圖片展示頁
console.log('request handler show wa called');
fs.readFile("temp/test.png",function (err,file) {
if (err) {
response.writeHead(500,{"content-type":"text/plain"});
response.write(err+'\n');
response.end();
}else{
response.writeHead(200,{"content-type":"image/png"});
response.write(file,"binary"); //以二進制形式寫進去
response.end();
}
})
}
exports.start = start;
exports.upload = upload;
exports.show = show;
訪問 http://localhost/start服赎, 是文件上傳界面,上傳完后地址是 http://localhost/upload 同時在同目錄的public/upload里存放了所有上傳的圖片