Home  >  Article  >  Backend Development  >  File upload and download management with PHP and mini-programs

File upload and download management with PHP and mini-programs

WBOY
WBOYOriginal
2023-07-06 09:19:361326browse

File upload and download management of PHP and mini programs

With the rapid development of the mobile Internet, mini programs have become the preferred development platform for more and more enterprises and individuals. In the development process of small programs, uploading and downloading files is one of the common requirements. This article will introduce how to use PHP to implement upload and download management of mini program files, and provide relevant code examples.

1. File upload

In mini programs, users often need to upload pictures, videos and other files. As a powerful server-side scripting language, PHP can easily handle file upload operations.

First, you need to add a file upload button and corresponding event handling function to the front-end part of the mini program. An example is as follows:

<view class="upload-btn" bindtap="chooseFile">
  <image src="upload.png"></image>
  <text>点击上传</text>
</view>

<!-- 小程序的wxml文件中添加了一个文件上传按钮 -->
chooseFile: function() {
  wx.chooseImage({
    success: function(res) {
      var tempFilePaths = res.tempFilePaths[0];
      wx.uploadFile({
        url: 'https://yourserver.com/upload.php',
        filePath: tempFilePaths,
        name: 'file',
        success: function(res) {
          console.log(res.data);
        }
      });
    }
  });
}

// 小程序的js文件中添加了选择文件和上传文件的处理函数

Then, use PHP on the server side to process the uploaded file. Create a file named upload.php and add the following code:

<?php
  $target_dir = "uploads/";
  $target_file = $target_dir . basename($_FILES["file"]["name"]);
  $uploadOk = 1;
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  // 判断上传的文件是否为真实的图片
  if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
      $uploadOk = 1;
    } else {
      echo "文件不是图片";
      $uploadOk = 0;
    }
  }

  // 检查文件是否已存在
  if (file_exists($target_file)) {
    echo "文件已存在";
    $uploadOk = 0;
  }

  // 检查文件大小
  if ($_FILES["file"]["size"] > 500000) {
    echo "文件过大";
    $uploadOk = 0;
  }

  // 允许上传的文件格式
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    echo "仅支持 JPG, JPEG, PNG, GIF 文件";
    $uploadOk = 0;
  }

  // 检查是否出现错误
  if ($uploadOk == 0) {
    echo "文件上传遇到错误";
  } else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
      echo "文件上传成功";
    } else {
      echo "文件上传失败";
    }
  }
?>

The above code will save the uploaded file in the uploads folder on the server and verify it based on the file type and size. If the upload is successful, a "File uploaded successfully" prompt will be printed in the mini program, otherwise a corresponding error message will be prompted.

2. File Download

In the mini program, users may need to download some files, such as PDF documents, audio files, etc. The following is a sample code that uses PHP to implement the file download function:

<?php
  $file_url = 'http://yourserver.com/files/sample.pdf'; // 下载文件的URL
  $file_name = basename($file_url);

  header('Content-Type: application/octet-stream'); // 指定下载文件的文件类型
  header("Content-Transfer-Encoding: Binary");
  header("Content-disposition: attachment; filename="" . $file_name . """);
  readfile($file_url); // 将文件发送到用户端
?>

In the above example, $file_url represents the URL of the file to be downloaded. Tell the browser to download the file by setting the header, and then use the readfile function to send the file to the user.

The above is a brief introduction and code example of using PHP to implement mini program file upload and download management. I hope this article can help readers better understand and apply these two functions, and play a role in actual development.

The above is the detailed content of File upload and download management with PHP and mini-programs. For more information, please follow other related articles on the PHP Chinese website!

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