2013-12-09 128 views
0

我想用nodejs上傳圖片。如何使用nodejs上傳文件

我發送文件到節點,但接下來的問題是,我不知道如何處理「請求」。

客戶

<html> 
    <body> 
     <input id="uploadInput" type="file"/> 
     <div id="uploadShow"></div> 

     <script type="text/javascript"> 
      uploadInput = document.getElementById("uploadInput"); 
      uploadInput.onchange = function() { //when file ready to upload 
       if(uploadInput.files && uploadInput.files[0]) { 
        var file = uploadInput.files[0]; //I want to send the file 
        var xhr = new XMLHttpRequest(); 

        if (xhr.readyState == 4 && xhr.status == 200) { 
         var uploadShow = document.getElementById("uploadInput"); 
         uploadShow.innerHTML = xhr.responseText; //show file 
        } 

        xhr.open('POST', "/upload", false); 
        xhr.send(file); //send file... 
       } 
      }; 
     </script> 
    </body> 
</html> 

服務器

var http = require('http'),url = require("url"), 
    path = require('path'),fs = require('fs'); 

http.createServer(function(req, res) { 
    var filename = "/index.html"; 
    if (req.url !== "/") { 
     filename = url.parse(req.url, true).pathname; 
     filename = filename.split("?")[0]; 
    } 
    if (filename === "/upload" && req.method.toLowerCase() == 'post') { 
     //deal the request of ajax 

     **upload_file**(req, res); //can you help me to write this function 

     return; 
    } 
    //the following fs.readFile index.html 

}).listen("192.168.39.9", 8888); 

我如何上傳圖像和顯示?

+0

'文件[0]'可能並沒有真正給你的文件,更像是高度,寬度的對象,以及URL''fakepath/image.png''或者什麼的,那只是一個字符串。該圖像將位於formData對象中。 – adeneo

回答