Use JavaScript functions to upload and download files
Nov 04, 2023 am 08:30 AMUse 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.
- 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); }
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.
- 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(); }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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 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

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

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

File Uploading and Processing in Laravel: Managing User Uploaded Files Introduction: File uploading is a very common functional requirement in modern web applications. In the Laravel framework, file uploading and processing becomes very simple and efficient. This article will introduce how to manage user-uploaded files in Laravel, including verification, storage, processing, and display of file uploads. 1. File upload File upload refers to uploading files from the client to the server. In Laravel, file uploads are very easy to handle. first,

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

JavaScript Function Asynchronous Programming: Essential Skills for Handling Complex Tasks Introduction: In modern front-end development, handling complex tasks has become an indispensable part. JavaScript function asynchronous programming skills are the key to solving these complex tasks. This article will introduce the basic concepts and common practical methods of JavaScript function asynchronous programming, and provide specific code examples to help readers better understand and use these techniques. 1. Basic concepts of asynchronous programming In traditional synchronous programming, the code is
