从零开始学习Node.js系列好代码教程三:图片上传和显示方法示例

四个拥有:无论你有多弱或多强,一定要拥有真正爱你的人,拥有知心的朋友,拥有向上的事业,拥有温暖的住所。

本文实例讲述了Node.js图片上传和显示方法。分享给大家供大家参考,具体如下:

index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;
server.start(router.route, handle);

server.js

var http = require("http");
var url = require("url");
function start(route, handle) {
 function onRequest(request, response) {
  var pathname = url.parse(request.url).pathname;
  console.log("Request for " + pathname + " received.");
  route(handle, pathname, response, request);
 }
 http.createServer(onRequest).listen(3000);
 console.log("Server has started.");
}
exports.start = start;

requestHandlers.js

var querystring = require("querystring"),
  fs = require("fs"),
  formidable = require("formidable");
function start(response) {
  console.log("Request handler 'start' was called.");
  var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" content="text/html; '+
    'charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/upload" enctype="multipart/form-data" '+
    'method="post">'+
    '<input type="file" name="upload" multiple="multiple">'+
    '<input type="submit" value="Upload file" />'+
    '</form>'+
    '</body>'+
    '</html>';
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(body);
  response.end();
}
function upload(response, request) {
  console.log("Request handler 'upload' was called.");
  var form = new formidable.IncomingForm();
  form.uploadDir = "D:\\min\\nodejsExample2\\tmp";
  console.log("about to parse1");
  form.parse(request, function(error, fields, files) {
    console.log("parsing done");
    console.log(files.upload.path);
    fs.renameSync(files.upload.path, "D:\\min\\nodejsExample2\\tmp\\test.png");
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    response.write("<img src='/show' />");
    response.end();
 });
}
function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile("D:\\min\\nodejsExample2\\tmp\\test.png", "binary", function(error, file) {
    if(error) {
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\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;

router.js

function route(handle, pathname, response, request) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response, request);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/html"});
    response.write("404 Not found");
    response.end();
  }
}
exports.route = route;

result:

知识点:

其中用到了fs模块的readFile读取文件,它有同步和异步两个版本。node.js中,并不是所有的API都提供了异步和同步版本,node.js不鼓励使用同步I/O。

//this is async 异步
/*
 fs.readFile调用时所做的工作只是将异步式I/O请求发送给了操作系统,然后立即返回并执行后面的语句,执行完以后进入事件循环监听事件。
 当fs接收到I/O请求完成的事件时,事件循环会主动调用回调函数以完成后续工作。
 */
var fs = require('fs');
fs.readFile('file.txt', 'utf-8', function(err, data){
  if (err){
    console.error(err);
  } else {
    console.log(data);
  }
});

//this is sync 同步
var fs = require('fs');
var data = fs.readFileSync('file.txt', 'utf-8');
console.log(data);
console.log('end.');

希望本文所述对大家nodejs程序设计有所帮助。

到此这篇关于从零开始学习Node.js系列好代码教程三:图片上传和显示方法示例就介绍到这了。青春的路上充满了彷徨。青春的热血在我们的身体中流淌,叛逆的力量在沉默中爆发。叛逆、 嚣张、 标新立异···是我们的标识。我们渴望成长,渴望挣脱种种的束缚,却又羽翼未丰。我们渴望能够独当一面,渴望被认可,却又能力不足。我们有满腔的基情与理想,可又无法释放。于是,我们纷纷发表独立宣言,希望得到大人世界的认可,我们纷纷反抗,希望挣脱束缚。我们徘徊在梦想与堕落的边缘,不知路在何方。更多相关从零开始学习Node.js系列好代码教程三:图片上传和显示方法示例内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
ajax上传图片到PHP并压缩图片显示的方法

Ajax实现图片上传并预览功能

ThinkPHP5 通过ajax插入图片并实时显示(完整代码)

基于Spring Boot利用 ajax实现上传图片功能

React+ajax+java实现上传图片并预览功能