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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.