轻松创建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读取JSON文件格式化时的注意事项
Sep 25 NodeJs
nodejs连接mongodb数据库实现增删改查
Dec 01 NodeJs
详解nodejs 文本操作模块-fs模块(一)
Dec 22 NodeJs
mac下的nodejs环境安装的步骤
May 24 NodeJs
nodejs socket实现的服务端和客户端功能示例
Jun 02 NodeJs
NodeJS实现图片上传代码(Express)
Jun 30 NodeJs
Nodejs中使用phantom将html转为pdf或图片格式的方法
Sep 18 NodeJs
nodejs+mongodb+vue前后台配置ueditor的示例代码
Jan 02 NodeJs
Nodejs Express 通过log4js写日志到Logstash(ELK)
Aug 30 NodeJs
Nodejs中的require函数的具体使用方法
Apr 02 NodeJs
nodejs实现日志读取、日志查找及日志刷新的方法分析
May 20 NodeJs
5分钟教你用nodeJS手写一个mock数据服务器的方法
Sep 10 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
《星际争霸II》全新指挥官斯台特曼现已上线
2020/03/08 星际争霸
php将数据库中所有内容生成静态html文档的代码
2010/04/12 PHP
CI操作cookie的方法分析(基于helper类库)
2016/03/28 PHP
PHP设计模式之工厂模式与单例模式
2016/09/28 PHP
验证坐标在某坐标区域内php代码
2016/10/08 PHP
PHP实现自动发送邮件功能代码(qq 邮箱)
2017/08/18 PHP
js类后台管理菜单类-MenuSwitch
2007/09/12 Javascript
JavaScript 验证码的实例代码(附效果图)
2013/03/22 Javascript
jQuery替换字符串(实例代码)
2013/11/13 Javascript
老生常谈JavaScript 正则表达式语法
2016/08/20 Javascript
vue.js从安装到搭建过程详解
2017/03/17 Javascript
微信小程序组件之srcoll-view的详解
2017/10/19 Javascript
小程序开发基础之view视图容器
2018/08/21 Javascript
JS代码触发事件代码实例
2020/01/02 Javascript
JavaScript实现密码强度实时验证
2020/03/18 Javascript
Django中模版的子目录与include标签的使用方法
2015/07/16 Python
Python的Django框架中URLconf相关的一些技巧整理
2015/07/18 Python
在windows下Python打印彩色字体的方法
2018/05/15 Python
python 3.6.2 安装配置方法图文教程
2018/09/18 Python
Python二进制文件读取并转换为浮点数详解
2019/06/25 Python
Django的models中on_delete参数详解
2019/07/16 Python
pytorch 预训练层的使用方法
2019/08/20 Python
Python 3.8正式发布,来尝鲜这些新特性吧
2019/10/15 Python
pycharm 2020 1.1的安装流程
2020/09/29 Python
HTML5 与 XHTML2
2008/10/17 HTML / CSS
浅谈HTML5中dialog元素尝鲜
2018/10/15 HTML / CSS
香港钟表珠宝首饰商城:OneMallTime网摩间
2016/10/14 全球购物
加拿大快时尚零售商:Ardene
2018/02/14 全球购物
公司任命书范本
2014/06/04 职场文书
国际商务英语专业求职信
2014/07/08 职场文书
村党支部书记个人对照材料汇报
2014/10/26 职场文书
2015年毕业生实习评语
2015/03/25 职场文书
通知范文怎么写
2015/04/16 职场文书
python 网络编程要点总结
2021/06/18 Python
Python开发工具Pycharm的安装以及使用步骤总结
2021/06/24 Python
在Windows Server 2012上安装 .NET Framework 3.5 所遇到的问题
2022/04/29 Servers