轻松创建nodejs服务器(10):处理上传图片


Posted in NodeJs onDecember 18, 2014

本节我们将实现,用户上传图片,并将该图片在浏览器中显示出来。

这里我们要用到的外部模块是Felix Geisendörfer开发的node-formidable模块。它对解析上传的文件数据做了很好的抽象。

要安装这个外部模块,需在cmd下执行命令:

npm install formidable

如果输出类似的信息就代表安装成功了:
npm info build Success: formidable@1.0.14

安装成功后我们用request将其引入即可:
var formidable = require(“formidable”);

这里该模块做的就是将通过HTTP POST请求提交的表单,在Node.js中可以被解析。我们要做的就是创建一个新的IncomingForm,它是对提交表单的抽象表示,之后,就可以用它解析request对象,获取表单中需要的数据字段。

本文案例的图片文件存储在 /tmp文件夹中。

我们先来解决一个问题:如何才能在浏览器中显示保存在本地硬盘中的文件?

我们使用fs模块来将文件读取到服务器中。

我们来添加/showURL的请求处理程序,该处理程序直接硬编码将文件/tmp/test.png内容展示到浏览器中。当然了,首先需要将该图片保存到这个位置才行。

我们队requestHandlers.js进行一些修改:

var querystring = require("querystring"),

 fs = require("fs");

function start(response, postData) {

 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" method="post">'+

    '<textarea name="text" rows="20" cols="60"></textarea>'+

    '<input type="submit" value="Submit text" />'+

    '</form>'+

    '</body>'+

    '</html>';

 response.writeHead(200, {"Content-Type": "text/html"});

 response.write(body);

 response.end();

}

function upload(response, postData) {

 console.log("Request handler 'upload' was called.");

 response.writeHead(200, {"Content-Type": "text/plain"});

 response.write("You've sent the text: "+ querystring.parse(postData).text);

 response.end();

}

function show(response, postData) {

 console.log("Request handler 'show' was called.");

 fs.readFile("/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;

我们还需要将这新的请求处理程序,添加到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);

重启服务器之后,通过访问http://localhost:8888/show,就可以看到保存在/tmp/test.png的图片了。

好,最后我们要的就是:

 在/start表单中添加一个文件上传元素

 将node-formidable整合到我们的upload请求处理程序中,用于将上传的图片保存到/tmp/test.png

 将上传的图片内嵌到/uploadURL输出的HTML中

第一项很简单。只需要在HTML表单中,添加一个multipart/form-data的编码类型,移除此前的文本区,添加一个文件上传组件,并将提交按钮的文案改为“Upload file”即可。 如下requestHandler.js所示:

var querystring = require("querystring"),

 fs = require("fs");

function start(response, postData) {

 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">'+

    '<input type="submit" value="Upload file" />'+

    '</form>'+

    '</body>'+

    '</html>';

 response.writeHead(200, {"Content-Type": "text/html"});

 response.write(body);

 response.end();

}

function upload(response, postData) {

 console.log("Request handler 'upload' was called.");

 response.writeHead(200, {"Content-Type": "text/plain"});

 response.write("You've sent the text: "+ querystring.parse(postData).text);

 response.end();

}

function show(response, postData) {

 console.log("Request handler 'show' was called.");

 fs.readFile("/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;

接下来,我们要完成第二步,我们从server.js开始 —— 移除对postData的处理以及request.setEncoding (这部分node-formidable自身会处理),转而采用将request对象传递给请求路由的方式:

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(8888);

 console.log("Server has started.");

}

exports.start = start;

接下来修改router.js,这次要传递request对象:

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;

现在,request对象就可以在我们的upload请求处理程序中使用了。node-formidable会处理将上传的文件保存到本地/tmp目录中,而我们需

要做的是确保该文件保存成/tmp/test.png。

接下来,我们把处理文件上传以及重命名的操作放到一起,如下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();

 console.log("about to parse");

 form.parse(request, function(error, fields, files) {

  console.log("parsing done");

  fs.renameSync(files.upload.path, "/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("/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;

做到这里,我们的服务器就全部完成了。

在执行图片上传的过程中,有的人可能会遇到这样的问题:

轻松创建nodejs服务器(10):处理上传图片

照成这个问题的原因我猜测是由于磁盘分区导致的,要解决这个问题就需要改变formidable的默认零时文件夹路径,保证和目标目录处于同一个磁盘分区。

我们找到requestHandlers.js的 upload函数,将它做一些修改:

function upload(response, request) { 

 console.log("Request handler 'upload' was called."); 

 var form = new formidable.IncomingForm(); 

 console.log("about to parse");

 

 form.uploadDir = "tmp";

 

 form.parse(request, function(error, fields, files) { 

  console.log("parsing done"); 

  fs.renameSync(files.upload.path, "/tmp/test.png"); 

  response.writeHead(200, {"Content-Type": "text/html"}); 

  response.write("received image:<br/>"); 

  response.write("<img src='/show' />"); 

  response.end(); 

 }); 

}

我们增加了一句 form.uploadDir = “tmp”,现在重启服务器,再执行上传操作,问题完美解决。
NodeJs 相关文章推荐
nodejs入门详解(多篇文章结合)
Mar 07 NodeJs
nodejs的require模块(文件模块/核心模块)及路径介绍
Jan 14 NodeJs
Nodejs为什么选择javascript为载体语言
Jan 13 NodeJs
nodejs中实现sleep功能实例
Mar 24 NodeJs
NodeJS使用formidable实现文件上传
Oct 27 NodeJs
nodejs根据ip数组在百度地图中进行定位
Mar 06 NodeJs
NodeJs实现简单的爬虫功能案例分析
Dec 05 NodeJs
NodeJS读取分析Nginx错误日志的方法
May 14 NodeJs
nodejs实现UDP组播示例方法
Nov 04 NodeJs
nodejs开发一个最简单的web服务器实例讲解
Jan 02 NodeJs
nodejs中使用worker_threads来创建新的线程的方法
Jan 22 NodeJs
浅谈JS和Nodejs中的事件驱动
May 05 NodeJs
轻松创建nodejs服务器(10):处理POST请求
Dec 18 #NodeJs
轻松创建nodejs服务器(7):阻塞操作的实现
Dec 18 #NodeJs
轻松创建nodejs服务器(8):非阻塞是如何实现的
Dec 18 #NodeJs
轻松创建nodejs服务器(9):实现非阻塞操作
Dec 18 #NodeJs
轻松创建nodejs服务器(6):作出响应
Dec 18 #NodeJs
轻松创建nodejs服务器(5):事件处理程序
Dec 18 #NodeJs
轻松创建nodejs服务器(4):路由
Dec 18 #NodeJs
You might like
PR值查询 | PageRank 查询
2006/12/20 PHP
ThinkPHP之用户注册登录留言完整实例
2014/07/22 PHP
PHP自定义错误用法示例
2016/09/28 PHP
jquery与google map api结合使用 控件,监听器
2010/03/04 Javascript
javascript中获取下个月一号,是星期几
2012/06/01 Javascript
js 定义对象数组(结合)多维数组方法
2016/07/27 Javascript
Windows环境下npm install 报错: operation not permitted, rename的解决方法
2016/09/26 Javascript
bootstrap table方法之expandRow-collapseRow展开或关闭当前行数据
2020/08/09 Javascript
微信小程序商品详情页规格属性选择示例代码
2017/10/30 Javascript
微信小程序模板和模块化用法实例分析
2017/11/28 Javascript
vue 监听屏幕高度的实例
2018/09/05 Javascript
[02:17]《辉夜杯》TRG战队巡礼
2015/10/26 DOTA
Python中input和raw_input的一点区别
2014/10/21 Python
仅利用30行Python代码来展示X算法
2015/04/01 Python
在Python中使用成员运算符的示例
2015/05/13 Python
python3通过selenium爬虫获取到dj商品的实例代码
2019/04/25 Python
pytorch之inception_v3的实现案例
2020/01/06 Python
python计算二维矩形IOU实例
2020/01/18 Python
Django models文件模型变更错误解决
2020/05/11 Python
python 实现的IP 存活扫描脚本
2020/12/10 Python
澳大利亚波西米亚风情网上商店:Czarina
2019/03/18 全球购物
c语言常见笔试题总结
2016/09/05 面试题
DBA的职责都有哪些
2012/05/16 面试题
微型企业创业投资计划书
2014/01/10 职场文书
工艺员岗位职责
2014/02/11 职场文书
艺术节主持词
2014/04/02 职场文书
小学生操行评语
2014/04/22 职场文书
高中课程设置方案
2014/05/28 职场文书
节电标语大全
2014/06/23 职场文书
小学生纪念九一八事变演讲稿
2014/09/14 职场文书
教师个人事迹材料
2014/12/17 职场文书
孟佩杰观后感
2015/06/17 职场文书
放假通知怎么写
2015/08/18 职场文书
Python中快速掌握Data Frame的常用操作
2021/03/31 Python
tomcat的catalina.out日志按自定义时间格式进行分割的操作方法
2022/04/02 Servers
漫画《尖帽子的魔法工坊》宣布动画化
2022/04/06 日漫