楼主要做一个简单的图片上传服务器, node.js实现服务端, 页面使用HTML5-Canvas实现截图。
为什么用Nodejs呢,因为用Js写后台很爽-。- 而且比较简单
为什么用canvas呢,其实我不想用的 因为有些低版本的IE对HTML5的支持不好,
楼主本来想用 HTML2CANVAS 来实现截图并且上传到一个服务器上。 (html2canvas 技术可以参照我另一篇博客 )
但是这个技术对于一些复杂的DOM就不适用了,比如EXTJS drawComponent画出来的东西完全是渣啊~~所以退而求其次,我把呈现测试用
HTML5的Canvas呈现出来,然后保存图片。
╮(╯▽╰)╭ 具体用处是公司的秘密
推荐一个教程,写的很简单明了:
下面的代码是我参照了这个教程的结构写的,如有雷同说明那货一定也是看了这个教程。
主页代码: Index.js
1 var server = require("./server");2 var route = require("./route");3 server.start(route.route);
server代码:
var http = require("http");var url = require("url");function start(route, handle) { function onRequest(request, response) { var postData = ""; var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); request.setEncoding("utf8"); request.addListener("data", function(postDataChunk) { postData += postDataChunk; console.log("Received POST data chunk '"+ postDataChunk + "'."); }); request.addListener("end", function() { route(pathname, response, postData); }); } http.createServer(onRequest).listen(8888); console.log("Server has started.");}exports.start = start;
route.js 代码:
1 function route(pathname,response,postData){ 2 var requestHandler=require("./requestHandler"); 3 if (typeof requestHandler.handle[pathname] === 'function') { 4 5 requestHandler.handle[pathname](response,postData); 6 response.end(); 7 } 8 else { 9 console.log("No request handler found for " +pathname);10 response.writeHead(404, {"Content-Type": "text/plain"});11 response.write("404 Not found");12 13 }14 }15 exports.route=route;
requestHandler.js 代码:
1 function start(response,postData) { 2 console.log("Request handler 'start' was called."); 3 4 response.writeHead(200, {"Content-Type": "text/html"}); 5 var body = ''+ 6 ''+ 7 ' '+ 9 ''+10 ''+11 ' '+''+''12 +''+13 14 '';15 response.write(body);16 response.end();17 }18 19 function upload(response,postData) {20 response.writeHead(200, {"Content-Type": "text/plain"});21 var fs = require('fs');22 var base64Data = postData.replace(/^data:image\/\w+;base64,/, "");23 var dataBuffer = new Buffer(base64Data, 'base64');24 console.log("Request handler 'upload' was called.");25 fs.writeFile("out.png", dataBuffer, function(err) {26 });27 response.write("hello");28 response.end();29 }30 var handle=[];31 handle['/start']=start;32 handle['/upload']=upload;33 handle['/']=start;34 exports.handle=handle;
其中,处理base64的图片数据用到了这个链接的技术:
程序运行结果 :
浏览器:
服务器目录: