2016-08-25 59 views
0

試圖使用multiparty上載服務器中的多個文件。在服務器端獲取兩個文件,但只寫入單個文件正在上傳。當我調試代碼時,我發現在文件讀取發生之前,控制器正在返回到for循環的開始處。因此,對象中的最新文件僅處理上傳。爲什麼發生這種情況?以下是相同的代碼。沒有上傳到node.js服務器的多個文件

form.parse(req, function(err, fields, files){ 
      var fileArry=files.uploadFiles; 
       if(fileArry.length == 0){ 
        console.log(" No file found to upload !!!"); 
        res.send('No files found to upload.'); 
          return; 
       } 
       for(var i=0; i<fileArry.length ; i++) 
       { 
        newPath='./uploads/'; 
        singleFile=fileArry[i]; 

        console.log("::::::::::::::::::::: This is the single file and it path ::::::::::::::::::::::::");       
        console.log(singleFile); 

        newPath+=singleFile.originalFilename; 

        console.log("::::::::::::::::::::: New file path is :"+newPath)   
        console.log("::::::::::::::::::::: Going inside file :::::::::::::::::::::::::::::::::::::::::::"); 

        fs.readFile(singleFile.path, (err, data) => { 
         fs.writeFile(newPath, data, (err) => {      
         console.log("Files uploaded "+newPath); 
            }); 
           });         
          } 
         res.send("File uploaded to: " + newPath); 
       }); 

調試後的結果是Image -

如何克服這一點,並上傳多個文件在同一時間?

回答

0

經過幾個小時的嘗試,並做了一些谷歌搜索遇到了類似的情況link和是的,它確實解決了我的問題。根據鏈接,更改後的代碼如下所示,並且可用於上傳多個文件。

app.post('/multiFileUpload', function(req, res) { 

    var singleFile;  
    var form = new multiparty.Form(); 

    form.parse(req, function(err, fields, files){  
     var fileArry=files.uploadFiles;     
       if(fileArry.length == 0){ 
        res.send('No files found to upload.'); 
         return; 
       } 

        for(i=0; i<fileArry.length; i++) 
        { 
         newPath='./uploads/'; 
         singleFile=fileArry[i]; 
         newPath+=singleFile.originalFilename; 
         readAndWriteFile(singleFile,newPath);      
        } 
        res.send("File uploaded to: " + newPath); 
      }); 

}); 

function readAndWriteFile(singleFile , newPath){ 

    fs.readFile(singleFile.path, (err, data)=>{ 
     fs.writeFile(newPath, data, (err)=>{                             
       console.log("File uploaded to :"+newPath); 
      }); 
    }); 
}