Detailed explanation of PHP material picture uploading and downloading functions

  • 2021-12-05 05:52:11
  • OfStack

The download here is to generate zip package for download, so ZipArchive () class of PHP is needed. With this class, zlib needs to be turned on for linux, and comments before php_zip. dll needs to be cancelled for windows. And does not include 3 parties such as oss

Upload

Upload is very simple, PHP comes with move_uploaded_file () function can use our simple file upload.

We just need to save the path of the file to the database, which is convenient for us to download or display when using OK.

Here, it is important to note that the uploaded path and file name should not include Chinese as much as possible.

Download

To download the file, we need to temporarily generate the zip package of 1 server, then set the request header and finally delete the temporary zip package generated by the server to OK. The following code is directly listed:


$filename = rand(0, 999).'.zip';
$zip = new ZipArchive();
/*
* $zip->open  The first part of this method 1 Parameter is the name of the file to process 
*  No. 1 2 Indicates the processing mode. 
* ZipArchive::CREATE The system will go to the original zip  Additional contents in the file 
* ZipArchive::OVERWRITE  Is to prevent the system from adding the same 1 Files to  zip  Medium 
*/
$zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
//  Add file contents to zip  Document 
$zip->addFromString(/* File name */ ,  /* File content */);

//  Set the request header, download the compressed package, and delete the temporary on the server  zip  Documents 
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-length: ".$filename); //  I want to splice yours in the back zip  Filename 
Header("Content-Disposition: attachment; filename=images.zip"); //  Here's  filename  It's what you want to download  zip  The name of the package 

// 1 Secondary transmission only 1024 Bytes of data to the client 
$buffer = 1024;
while(!feof($file)) {
 //  Read a file into memory 
 $file_data = fread($file, $buffer);
 //  Echo back to the client every time 1024 Bytes 
 echo $file_data;
}

fclose($file);
unlink($filename); //  Delete a file 
exit;

Related articles: