2016-10-02 111 views
0

我想錄制視頻並上傳到服務器。我可以製作視頻,但上傳不起作用。我可能做錯了什麼。我試圖直接從服務器(a.click())下載文件。它的工作原理,但我無法上傳到nodejs服務器使用POST的JavaScript文件上傳Nodejs

我能夠發佈文本值並從服務器獲取我能夠上傳文件使用html中的表單從文件系統中選擇並傳遞一個文件直接選擇它..below

<form id="uploadForm" 
     enctype="multipart/form-data" 
     action="/upload" 
     method="post"> 
    <input type="file" name="file" /> 
    <input type="submit" value="Upload Image" name="submit"> 
    <span id = "status"></span> 
</form> 

我還可以用socket.io發送的文件,如果是做socket.emit(「味精」,文件),但我不能在PROD環境中使用插座。我願意接受任何其他方式來發送記錄文件的NodeJS服務器

服務器代碼

var express \t = \t require("express"); 
 
var multer \t = \t require('multer'); 
 

 
var app \t = \t express(); 
 
var fs = require('fs'); 
 
var storage \t = \t multer.diskStorage({ 
 
    destination: function (req, file, callback) { 
 
    callback(null, './uploads'); 
 
    }, 
 
    filename: function (req, file, cb) { 
 
       var datetimestamp = Date.now(); 
 
       cb(null, file.originalname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]) 
 
      } 
 
    }); 
 
var upload = multer({ storage : storage}).single('file'); 
 
app.get('/',function(req,res){ 
 
     res.sendFile(__dirname + "/index.html"); 
 
}); 
 
app.post('/uploadlocal',function(req,res){ 
 

 
\t upload(req,res,function(err) {console.log(req.files); 
 
\t console.log(req.body); 
 

 
\t \t if(err) { 
 
\t \t \t return res.end("Error uploading file."); 
 
\t \t } 
 
\t 
 
\t \t res.end("File is uploaded"); 
 
\t }); 
 
}); 
 

 

 

 
app.listen(3000,function(){ 
 
    console.log("Working on port 3000"); 
 
});

客戶端代碼

function download() { 
 
    var blob = new Blob(recordedBlobs, {type: 'video/webm'}); 
 
    var url = window.URL.createObjectURL(blob); 
 
     var files = { 
 

 
            video: { 
 
             type: 'video/webm', 
 
             dataURL: url 
 
            } 
 
          }; 
 
    console.log('recording done'); 
 

 
    var a = document.createElement('a'); 
 
    a.style.display = 'none'; 
 
    a.href = url; 
 
    a.download = 'test.webm'; 
 
    document.body.appendChild(a); 
 
a.click(); 
 
    postclick(files); 
 

 
    setTimeout(function() { 
 
    document.body.removeChild(a); 
 
    window.URL.revokeObjectURL(url); 
 
    }, 100); 
 
} 
 

 

 
function postclick(data) { 
 
    var form = $('<form></form>'); 
 

 
    form.attr("method", "post"); 
 
    form.attr("action", '/uploadlocal'); 
 
    var field = $('<input></input>'); 
 
    field.attr("type", "text"); 
 
\t field.attr("name", 'file'); 
 
    field.attr("value", data); 
 

 
     form.append(field); 
 
    $(document.body).append(form); 
 
    form.submit(); 
 
}

+0

您可以確認您嘗試上傳文件的文件夾是否設置了所有必需的讀/寫權限? –

+0

權限沒問題 –

+0

有兩件事,你是否已經在你的'

'標籤中正確設置了'enctype',你是否也在'

回答

0

創造解決問題xmlhttprequest

var formData = new FormData(); 
formData.append('file', blob, "test.webm"); 
var request = new XMLHttpRequest(); 
request.open("POST", "/upload"); 
request.send(formData);