2014-10-05 39 views
7

我正在使用船長一次上傳多個文件到本地文件夾。但是我遇到了一些問題。在sails.js中處理上傳與船長(進展中)

upload: function (req, res) { 
    if (_.isEmpty(req.session.User)){ 
     return res.json({          //---> 1 
        success: 0 
       }); 
    }else{ 
     res.setTimeout(0); 
     var MAXBYTES = 10*1000*1000; 

                   //---> 2 
     if (req._fileparser.form.bytesExpected > MAXBYTES){ 
      return res.json({ 
       success: 0, 
       error: 'File size limit exceeded.' 
      }); 
     }else{ 

      req.file('file[]').on('progress', function(event){ 
       return event;         //---> 3 
      }).upload({ 

       maxBytes: MAXBYTES 

      }, function whenDone(err, uploadedFiles) { 
                   //---> 4 
        return res.json({ 
         success: 1, 
        }); 

      }); 
     } 
    } 
}, 

第一個錯誤//---> 1如果用戶沒有登錄,我想結束這種上傳過程並返回成功= 0,這是行不通的。在客戶端,請求保持懸掛而沒有任何迴應。

第二個錯誤//---> 2我遇到了一個錯誤,如前所述https://github.com/balderdashy/skipper/issues/36,所以作爲一個快速修復我使用了在github上的評論中使用的人。但同樣在問題1中,我遇到了這個問題。如果文件大小超過MAXBYTES的文件大小,我想結束這個上傳過程,並將成功= 0返回給用戶。這不會回到客戶端。

第三個錯誤//---> 3我想用進度來創建一個進度條。但我很快遇到了幾個問題。首先,使用進度會降低系統的速度。它也會導致第4步中的錯誤。

第四個錯誤//---> 4如果我們從步驟3中刪除on('progress'),則按預期工作。完成上傳後,它將成功= 1返回給客戶端。但是,當('進度')出現時return res...在步驟//---> 4不起作用,並且客戶端請求再次保持掛起而沒有任何響應。

幾個問題:爲什麼 不//---> 1下面的代碼工作,而工作在//---> 4如果在(「進步」)不存在

return res.json({ 
    success: 0 
}); 

爲什麼進度減慢上傳過程非常?

btw在我的客戶端我使用form.js插件。因此,我的要求是這樣的:

$('#upload').ajaxForm({ 
    uploadProgress: function(event, position, total, percentComplete){ 
     console.log(percentComplete); 
    }, 
    success: function(data) { 
     console.log(data); 
    } 
}); 

回答

4

我花了一些時間來解決這個問題,和我做的時候,我已經完全忘記了我的問題在這裏計算器。這些是我爲完成這項工作而採取的一些步驟。

upload: function (req, res) { 
    if (_.isEmpty(req.session.User)){ 
     return res.json({ // or destroy connection as shown below 
      success: 0 
     }); 
    }else{ 
     res.setTimeout(0); 
     var MAXBYTES = 10*1000*1000; 

     if (req._fileparser.form.bytesExpected && req._fileparser.form.bytesExpected > MAXBYTES) { 
      // file size exceeded //-> also check filesize on client-size before uploading because this will not send error report back to the client 
      req.connection.destroy(); 
     } 

     req.file('file[]').on('progress', function(event){ 
      // returning anything here was unnecessary 
      // For example jQuery form plugin's client-side `uploadProgress:` will still catch the progress 
     }).upload({ 
      maxBytes: MAXBYTES 
     }, function whenDone(err, uploadedFiles) { 
      var tempFileNames = _.pluck(uploadedFiles, 'fd'); 
      if (_.isEmpty(tempFileNames)) { 
       return res.json({ 
        success: 0, 
        error: '0 files selected.' 
       }); 
      }else{ 
       // process upload 
       return res.json({ 
        success: 1, 
       }); 
      } 
     }); 
    } 
}, 

這仍然不是最好的解決方案。我實際上發現它有些黑客。如果有人有更好的解決方案,請分享。