How to use ThinkPHP6 to upload and download large files?
With the continuous development of Internet technology, file uploading and downloading have become indispensable functions in the website development process. The efficiency and stability of the program become particularly important when handling large file uploads and downloads. ThinkPHP6 is a powerful PHP framework that can help us effectively implement large file upload and download functions.
1. Large file upload
When using ThinkPHP6 to upload large files, you need to consider the following aspects:
- You need to use multi-part upload on the front end Technology, that is, splitting the file into multiple small files for uploading. This can effectively avoid problems such as network interruptions when uploading large files.
- You need to use fragment merging technology on the backend, that is, merging small files uploaded in fragments into a complete large file. This needs to be achieved using PHP's file operation functions.
The following is a simple large file upload code example:
//Define the method of large file upload in the controller
public function upload()
{
$chunk = input('param.chunk'); // 获取当前上传的分片序号 $chunks = input('param.chunks'); // 获取分片总数 $file = request()->file('file'); // 获取上传的文件 $md5 = md5_file($file->getRealPath()); // 获取上传文件的MD5值 $fileName = $md5 . '_' . $chunk . '.part'; // 拼接分片文件名 $file->move('./uploads/', $fileName); // 保存分片文件到服务器 if ($chunk === $chunks - 1) { // 如果是最后一个分片文件 $filePath = './uploads/' . $md5 . '_' . time() . '.mp4'; // 拼接最终文件名 $fp = fopen($filePath, 'ab'); // 打开最终文件 for ($i = 0; $i < $chunks; $i++) { // 循环读取分片文件并写入到最终文件 $partFileName = './uploads/' . $md5 . '_' . $i . '.part'; // 获取分片文件名 $partFile = fopen($partFileName, 'rb'); fwrite($fp, fread($partFile, filesize($partFileName))); // 写入到最终文件 fclose($partFile); // 关闭分片文件 unlink($partFileName); // 删除分片文件 } fclose($fp); // 关闭最终文件 return '上传完成'; } else { return '上传中'; }
}
On the front-end page, you can use JavaScript to implement multipart upload:
function uploadFile(file) {
const size = file.size; const chunkSize = 1024 * 1024; // 将文件分割成1M大小的分片 const chunkCount = Math.ceil(size / chunkSize); // 计算分片数量 let currentChunk = 0; while (currentChunk < chunkCount) { const start = currentChunk * chunkSize; const end = (currentChunk + 1) * chunkSize; const blobChunk = file.slice(start, end); // 获取当前分片的Blob对象 const formData = new FormData(); formData.append('chunk', currentChunk); formData.append('chunks', chunkCount); formData.append('file', blobChunk); const xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.onload = function () { if (xhr.status !== 200) { console.error('文件上传失败'); return; } const responseText = xhr.responseText; console.log(responseText); if (responseText === '上传完成') { console.log('文件上传成功'); } else { console.log('正在上传...'); } }; xhr.send(formData); currentChunk++; }
}
2. Large file download
When dealing with large file downloads, we need to consider the following aspects:
- The file size must be taken into consideration when downloading files. If If the file is large, segmented download technology needs to be used, that is, the file content is read in segments and sent to the client. This can effectively avoid memory corruption problems.
- If you want to implement the breakpoint resume function, you need to record the file size that the client has downloaded. When the server reads the file content, you need to specify the reading starting position and length.
The following is a code example to implement large file download:
// Define the large file download method in the controller
public function download()
{
$filePath = './videos/big.mp4'; // 要下载的文件路径 $fileSize = filesize($filePath); // 获取文件大小 header('Content-Disposition: attachment; filename="big.mp4"'); // 设置文件下载名字 header('Content-Type: video/mp4'); // 设置文件类型 header('Content-Length: ' . $fileSize); // 设置文件大小 if (isset($_SERVER['HTTP_RANGE'])) { // 如果设置了HTTP_RANGE,说明是断点续传请求 header('HTTP/1.1 206 Partial Content'); list($start, $end) = explode('-', $_SERVER['HTTP_RANGE']); // 获取已经下载的起始位置和结束位置 $start = max(0, intval($start)); $end = min($fileSize - 1, intval($end)); header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize); $length = $end - $start + 1; } else { // 否则是首次请求 $start = 0; $end = $fileSize - 1; $length = $fileSize; } header('Accept-Ranges: bytes'); $fp = fopen($filePath, 'rb'); fseek($fp, $start); while (!feof($fp) && !connection_aborted() && $start <= $end) { set_time_limit(0); $buffer = fread($fp, min(1024 * 1024, $length)); // 分段读取文件内容 echo $buffer; $start += strlen($buffer); $length -= strlen($buffer); flush(); // 清除输出缓存 } fclose($fp);
}
On the front-end page, you can use JavaScript to download large files:
function downloadFile(url) {
const request = new XMLHttpRequest(); request.open('GET', url, true); request.onprogress = function (evt) { const progress = (evt.loaded / evt.total) * 100; console.log(`下载进度: ${progress.toFixed(2)}%`); }; request.send();
}
In short, using ThinkPHP6, we can more easily implement large file upload and download functions, allowing website users to share and transfer large files quickly and easily.
The above is the detailed content of How to use ThinkPHP6 to upload and download large files?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics



To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Recently, many users have come to ask me how to download the Kuaishou computer version. Below, the editor will bring you the operation method of downloading the Kuaishou computer version. Interested users, please come and learn below. Find the Game Center app on the home page; open Game Center, click the search bar in the upper right corner; enter "Kuaishou" in the search bar, and then click the magnifying glass icon on the right to search. Find the familiar "Kuaishou" icon and click the "Install" button; wait a moment and the Kuaishou APP will automatically download and complete the installation. Then return to the main page, you can see that Kuaishou is already on our simulator desktop, click to start.
