在我的代码中,我没有使用表单标记将表单数据提交给服务器。相反,我尝试使用fields
标识id
并使用JQuery
发送它。我的代码如下:
我需要将enctype
作为multipart/form-data
传递。我怎么能从JQuery这样做?
使用form
标记完成以下代码。有用。但是,我需要通过JQuery发送请求。我该怎么做?
使用FORM
代码
<form action="/" method="post" enctype="multipart/form-data" >
<input name="fileis" type="file" ></br>
<input type="submit" value="submit" />
</form>
我想要的是在不使用表单标签的情况下向/
发送请求。我的代码如下:
HTML
<input type="file" name="fileis" id="uploadinput" ></br>
JQUERY - 如何传递enctype
?
$('#uploadinput').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();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('uploads[]', file, file.name);
}
$.ajax({
url: '/',
type: 'post',
data: formData,
processData: false,
contentType: false,
cache: 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;
}
});
}
});