nodejs之上传图片并且显示图片

本节介绍做个例子,实现上传图片,并且显示图片,中间修改了原作者demo中的bug。

之前教程中的例子都可以脱离nodejs的目录依赖,即放在任何位置都可以执行,本节的例子和编译环境都必须放在nodejs的目录下,因为牵涉到路径的问题。

安装外部模块
首先我们要安装一个外部模块,该模块是Felix Geisend?rfer开发的node-formidable模块。它对解析上传的文件数据做了很好的抽象。 其实说白了,处理文件上传“就是”处理POST数据 —— 但是,麻烦的是在具体的处理细节,所以,这里采用现成的方案更合适点。

使用该模块,首先需要安装该模块。Node.js有它自己的包管理器,叫NPM。它可以让安装Node.js的外部模块变得非常方便。通过如下一条命令就可以完成该模块的安装:

1.先进入到nodejs的安装路径

cd C:\Program Files (x86)\nodejs

2.下载模块

npm install formidable

注:安装外部模块需要进入nodejs的根目录来执行npm指令

引用外部模块
现在我们就可以用formidable模块了——使用外部模块与内部模块类似,用require语句将其引入即可:

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

注:想要能引用到formidable,必须把你的项目放在nodejs的安装目录下,否则会出现下面的错误

requestHandlers的模块
 

应用程序需要新的部件,因此加入新的模块 -- 已经无需为此感到新奇了。我们来创建一个叫做requestHandlers的模块,并对于每一个请求处理程序,添加一个占位用函数,随后将这些函数作为模块的方法导出:

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"); 
    console.log(files.upload.path); 
    //fs.renameSync(files.upload.path, "/tmp/test.png"); 这个会报错,这个应该是linux的路径  
    fs.renameSync(files.upload.path, "./upload/test.png"); //winodw认的路径,nodejs的安装路径  
    //fs.renameSync(files.upload.path, "d:/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."); 
  //winodw认的路径,nodejs的安装路径  
  fs.readFile("./upload/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模块
 

通过检查给定的路径对应的请求处理程序是否存在,如果存在的话直接调用相应的函数

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; 
server模块
 

处理请求模块

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(8888); 
  console.log("Server has started."); 

 
exports.start = start; 
index模块
 

启动模块,主模块

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); 
运行后效果
如果现在启动应用(node index.js,始终记得这个命令行),随后请求一个URL,我请求的分别是是http://localhost:8888/,上传文件提交后,页面就会显示该图片了,并且硬盘也会存在该文件。

 

硬盘中的文件

 

 

nodejs执行的结果

浏览器中显示的结果


本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2012-10/72627p7.htm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Node.js中实现图片上传功能可以使用koa-body和koa-static这两个插件。首先,需要安装koa-body插件并在app.js配置中引入它。通过设置app.use(bodyParser.json({limit: '50mb'}))和app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))来限制post文件的大小。然后,设置视图引擎和模板配置,可以使用art-template插件来处理视图。最后,通过app.use('/', routes)将路由设置为根路径。\[1\] 具体实现图片上传功能的流程如下: 1. 前端通过接口将图片上传到后端。 2. 后端接收并验证图片。 3. 后端将图片存储在文件服务器上,并生成图片路径和唯一ID。 4. 后端将图片路径和唯一ID返回给前端。 5. 前端将图片路径和唯一ID发送到相应的接口中。 6. 接口保存图片信息以便后续使用。 这样,前端就可以通过图片路径和唯一ID来使用上传的图片了。\[3\] 总结起来,Node.js实现图片上传功能需要使用koa-body和koa-static插件,并按照上述流程进行处理。\[2\] #### 引用[.reference_title] - *1* [nodejs图片上传](https://blog.csdn.net/chunyouhai5703/article/details/100978631)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [《NodeJS》Koa实现图片上传功能](https://blog.csdn.net/zy21131437/article/details/130440198)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值