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

接下来,我们要完成第二步,我们从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" 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='https://www.jb51.net/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):处理上传图片

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxfsj.html