乐闻世界logo
搜索文章和话题

How to use FormData for AJAX file upload?

1个答案

1

Basic Steps for Uploading Files Using FormData and AJAX:

  1. Create an HTML Form: First, create an HTML form that allows users to select files.
html
<form id="fileUploadForm"> <input type="file" id="fileInput" name="file" /> <button type="button" onclick="uploadFile()">Upload File</button> </form>
  1. Constructing the FormData Object: In JavaScript, after the user selects a file, collect the file data using the FormData object.
javascript
function uploadFile() { var fileInput = document.getElementById('fileInput'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); }

Here, the append method of FormData adds the file. The first parameter specifies the key (which corresponds to the field name on the server), and the second parameter is the file itself.

  1. Sending the AJAX Request: Finally, use AJAX (such as XMLHttpRequest or the modern Fetch API) to asynchronously upload the file.

Using XMLHttpRequest:

javascript
function uploadFile() { var fileInput = document.getElementById('fileInput'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.onload = function () { if (xhr.status === 200) { alert('File upload successful'); } else { alert('File upload failed'); } }; xhr.send(formData); }

Using Fetch API:

javascript
function uploadFile() { var fileInput = document.getElementById('fileInput'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); fetch('/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error)); }

Example Explanation:

  • HTML Form allows users to select the file to upload.
  • JavaScript creates the FormData object and adds file data using the append method.
  • Using AJAX (whether XMLHttpRequest or Fetch API), we send a POST request to the server's /upload endpoint. This request includes the file data selected by the user.

Using this method, you can achieve file uploads without page refreshes, enhancing user experience.

2024年7月26日 21:42 回复

你的答案