2013-12-09 3 views
0

Я хочу обновить изображение с помощью nodejs.Как загрузить файл с nodejs

Я отправляю файл на узел, но следующий вопрос заключается в том, что я не знаю, как обращаться с «req».

Client

<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

ответ

0

Я не думаю, что загрузка файлов будет работать именно так. Если вы используете экспресс, я предлагаю вам использовать огромную поддерживаемую загрузку файла ajax;

Проверьте это здесь: https://stackoverflow.com/a/20372845/1520518

Смежные вопросы