📜  如何使用 JavaScript 在没有表单的情况下上传文件?

📅  最后修改于: 2021-11-08 06:38:53             🧑  作者: Mango

有几种方法可以在不使用 JavaScript 表单的情况下上传文件:

方式一:这种方式是使用FormData ,无需使用任何表单即可上传文件。这方面的特殊之处在于网络方法,例如 fetch,可以接受 FormData 对象作为主体。它使用 Content-Type — multipart/form-data 进行编码和发送。

JavaScript 代码段:

Javascript
var gfg = new FormData();
 
gfg.append('pictureFile',
        pictureInput.files[0]);
 
// upload.php is the file to be uploaded
$.ajax({
    url: 'upload.php',
    type: 'POST',
    processData: false,
    contentType: false,
    dataType: 'json',
    data: gfg
});


Javascript
// JavaScript Code
var form = document.getElementById('the-form');
 
form.onsubmit = function () {
    var formData = new FormData(form);
    formData.append('file', file);
    var xhr = new XMLHttpRequest();
 
    // Add any event handlers here...
    xhr.open('POST', form.getAttribute('action'), true);
    xhr.send(formData);
 
    // To avoid actual submission of the form
    return false;
}


HTML


 

    

Welcome To GFG

                       


Javascript
$('#simpleUpload').simpleUpload({
 
    // upload.php is the file
    // to be uploaded
    url: 'upload.php',
    trigger: '#upload',
    success: function (data) {
        alert('Successfully Uploaded');
    }
});


方式二:这种方式是使用可以直接上传文件的XMLHTTPRequest作为POST请求正文里面的内容。

JavaScript 代码段:

Javascript

// JavaScript Code
var form = document.getElementById('the-form');
 
form.onsubmit = function () {
    var formData = new FormData(form);
    formData.append('file', file);
    var xhr = new XMLHttpRequest();
 
    // Add any event handlers here...
    xhr.open('POST', form.getAttribute('action'), true);
    xhr.send(formData);
 
    // To avoid actual submission of the form
    return false;
}

方法三:这种方法是使用simpleUpload插件。

HTML 代码片段:

HTML



 

    

Welcome To GFG

                       

JavaScript 代码段:

Javascript

$('#simpleUpload').simpleUpload({
 
    // upload.php is the file
    // to be uploaded
    url: 'upload.php',
    trigger: '#upload',
    success: function (data) {
        alert('Successfully Uploaded');
    }
});

输出: