国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

輕松創建nodejs服務器(10):處理上傳圖片

2019-11-20 13:39:51
字體:
來源:轉載
供稿:網友

本節我們將實現,用戶上傳圖片,并將該圖片在瀏覽器中顯示出來。

這里我們要用到的外部模塊是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;

做到這里,我們的服務器就全部完成了。

在執行圖片上傳的過程中,有的人可能會遇到這樣的問題:

照成這個問題的原因我猜測是由于磁盤分區導致的,要解決這個問題就需要改變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”,現在重啟服務器,再執行上傳操作,問題完美解決。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 华蓥市| 集安市| 盈江县| 东至县| 镇宁| 桂东县| 巴楚县| 韩城市| 环江| 元江| 河曲县| 秭归县| 本溪市| 永善县| 祁阳县| 饶阳县| 德阳市| 梁河县| 阿拉善右旗| 汉中市| 育儿| 左权县| 炎陵县| 康定县| 游戏| 大关县| 英山县| 长春市| 香港 | 琼中| 信阳市| 宿州市| 古田县| 永定县| 连江县| 牟定县| 宁蒗| 湟源县| 辽阳县| 乌苏市| 买车|