Home Web Front-end JS Tutorial Use JavaScript functions to upload and download files

Use JavaScript functions to upload and download files

Nov 04, 2023 am 08:30 AM
File Upload Download Document javascript function

Use JavaScript functions to upload and download files

Use JavaScript functions to implement file upload and download

With the development and popularization of the Internet, file upload and download have become one of the common functions in web applications. This article will introduce how to use JavaScript functions to implement file upload and download functions, and provide specific code examples.

  1. File upload

File upload refers to uploading local files to the server through the web page. File API is provided in HTML5 to handle file selection and upload. We can use the FileReader object in the File API to read the file content and send the file to the server through the XMLHttpRequest object.

The following is a JavaScript function code example to implement file upload:

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.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      alert('文件上传成功');
    }
  };
  xhr.send(formData);
}
Copy after login

In the above code, we first obtain the DOM object of the file selection box, and then remove the selected file. Next, create a FormData object and add the selected files to the FormData. Then, create an XMLHttpRequest object and use the open() method to specify the upload URL and request method. Monitor the status change of XMLHttpRequest through the onreadystatechange event. When the status is 4 and the status code is 200, it means the file upload is successful. Finally, call the send() method to send the FormData to the server.

  1. File download

File download refers to downloading files from the server to the local. In JavaScript, you can download a file by creating a <a> element with a file download link and simulating a click.

The following is an example of JavaScript function code to implement file download:

function downloadFile() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', '/download', true);
  xhr.responseType = 'blob';
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var blob = xhr.response;
      var link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'file.txt';
      link.click();
    }
  };
  xhr.send();
}
Copy after login

In the above code, we first create an XMLHttpRequest object and use the open() method to specify the download URL and request method. for GET. Set responseType to 'blob' to receive the file as binary data. Monitor the status change of XMLHttpRequest through the onreadystatechange event. When the status is 4 and the status code is 200, it means the file download is successful. Then, by creating a <a> element, convert the response blob object into a URL, and assign the URL to the href attribute of the <a> element. Set the filename to 'downloaded.txt'. Finally, simulate clicking on the <a> element to trigger the file download.

In summary, by using JavaScript functions, we can easily implement file upload and download functions. Through the File API and XMLHttpRequest object, we can read and send files. By creating the <a> element and simulating a click, we can download the file. In actual applications, we can expand and optimize these functions according to specific needs.

The above is the detailed content of Use JavaScript functions to upload and download files. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python opening operation after downloading the file Python opening operation after downloading the file Apr 03, 2024 pm 03:39 PM

Python provides the following options to open downloaded files: open() function: open the file using the specified path and mode (such as 'r', 'w', 'a'). Requests library: Use its download() method to automatically assign a name and open the file directly. Pathlib library: Use write_bytes() and read_text() methods to write and read file contents.

How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

How to solve Java file upload exception (FileUploadException) How to solve Java file upload exception (FileUploadException) Aug 18, 2023 pm 12:11 PM

How to solve Java file upload exception (FileUploadException). One problem that is often encountered in web development is FileUploadException (file upload exception). It may occur due to various reasons such as file size exceeding limit, file format mismatch, or incorrect server configuration. This article describes some ways to solve these problems and provides corresponding code examples. Limit the size of uploaded files In most scenarios, limit the file size

How to use Hyperf framework for file downloading How to use Hyperf framework for file downloading Oct 21, 2023 am 08:23 AM

How to use the Hyperf framework for file downloading Introduction: File downloading is a common requirement when developing web applications using the Hyperf framework. This article will introduce how to use the Hyperf framework for file downloading, including specific code examples. 1. Preparation Before starting, make sure you have installed the Hyperf framework and successfully created a Hyperf application. 2. Create a file download controller First, we need to create a controller to handle file download requests. Open the terminal and enter

PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files Jul 30, 2023 pm 02:03 PM

PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files In developing web applications, file upload is a common requirement. PHP provides a convenient function move_uploaded_file() for processing uploaded files. This article will introduce you how to use this function to implement the file upload function. 1. Preparation Before starting, make sure that your PHP environment has been configured with file upload parameters. You can do this by opening php.in

How to trigger file download when clicking HTML button or JavaScript? How to trigger file download when clicking HTML button or JavaScript? Sep 12, 2023 pm 12:49 PM

Nowadays, many applications allow users to upload and download files. For example, plagiarism detection tools allow users to upload a document file that contains some text. It then checks for plagiarism and generates a report that users can download. Everyone knows how to use inputtypefile to create a file upload button, but few developers know how to use JavaScript/JQuery to create a file download button. This tutorial will teach you various ways to trigger a file download when an HTML button or JavaScript is clicked. Use HTML's <a> tag and download attribute to trigger file download when the button is clicked. Whenever we give the <a> tag

See all articles