我需要從我的HTML
頁面上傳圖像文件。但是,我不打算使用form
標籤,因爲還有其他form
字段(文本字段,複選框等)將用於稍後將數據傳遞到服務器。將圖像從JQuery上傳到Node JS
我的後臺在Node JS
。所有我想要的是從Node Js
結束檢索圖像數據(文件)。我怎樣才能做到這一點
HTML
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-body">
<span class="glyphicon glyphicon-cloud-upload"></span>
<h2>File Uploader</h2>
<h4>coligo.io</h4>
<div class="progress">
<div class="progress-bar" role="progressbar"></div>
</div>
<button class="btn btn-lg upload-btn" type="button">Upload File</button>
</div>
</div>
</div>
</div>
</div>
<input id="upload-input" type="file" name="uploads" multiple="multiple"></br>
JQuery的
$('.upload-btn').on('click', function(){
$('#upload-input').click();
$('.progress-bar').text('0%');
$('.progress-bar').width('0%');
});
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
// create a FormData object which will be sent as the data payload in the
// AJAX request
var formData = new FormData();
// loop through all the selected files and add them to the formData object
for (var i = 0; i < files.length; i++) {
var file = files[i];
var tmppath = URL.createObjectURL(event.target.files[0]);
// add the files to formData object for the data payload
formData.append('uploads', tmppath);
}
$.ajax({
url: '/myp/imgup',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!\n' + data);
},
xhr: function() {
// create an XMLHttpRequest
var xhr = new XMLHttpRequest();
// listen to the 'progress' event
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
// calculate the percentage of upload completed
var percentComplete = evt.loaded/evt.total;
percentComplete = parseInt(percentComplete * 100);
// update the Bootstrap progress bar with the new percentage
$('.progress-bar').text(percentComplete + '%');
$('.progress-bar').width(percentComplete + '%');
// once the upload reaches 100%, set the progress bar text to done
if (percentComplete === 100) {
$('.progress-bar').html('Done');
}
}
}, false);
return xhr;
}
});
}
});
NODE JS
router.post('/imgup', function(req, res){
console.log(' File name '+req.files.upload);
});
我一直在嘗試了這一點了好幾天,沒有運氣。有人可以幫我嗎。
https://github.com/felixge/node-formidable –
我已經厭倦了這個,但它沒用。可能是我在代碼中以錯誤的方式應用了它。你能告訴我它是如何完成的嗎? – Illep
這個答案怎麼樣http://stackoverflow.com/a/34442688/747579? –