search
HomeBackend DevelopmentPHP TutorialHow to download files from WeChat applet through back-end PHP


Scenario: The WeChat applet calls the wx.downloadFile() API to download a file, and the PHP backend performs processing and returns the file process;
Process:
1. The applet displays a list of files that need to be downloaded;
2. Click download and request the PHP interface, carrying a parameter for the name of the file you want to download;
3. Receive the parameter in PHP, and then search the folder to see if there is the file;
4. Find file and return the file to the applet;
5. The applet saves the file returned by the backend, click to open the file, and preview the code:
wxml

<view>文件列表</view>
<view wx:for=&#39;{{search_store}}&#39; wx:key=&#39;{{index}}&#39;>
  <view bindtap=&#39;dom&#39; id=&#39;{{index}}&#39;>文件名:{{item.fileName}} 点击下载</view>
</view>

js

  dom: function (e) {
    var index = e.currentTarget.id;
    var data = this.data.search_store[index].fileName
    var that = this;
    wx.downloadFile({
      url: &#39;https://dwb.lynncain.cn/H5/dom.php?str=&#39; + data, //下载路径携带 参数=文件名
      success: function (res) {
        console.log(res.tempFilePath)
        wx.saveFile({ //下载成功后保存
          tempFilePath: res.tempFilePath,
          success: function (res) {
           wx.showToast({
             title: &#39;下载成功!&#39;,
           })
           wx.getSavedFileList({ //获取下载的文件列表保存到data
             success: function (rrr) {
               console.log(rrr.fileList)
               that.setData({
                 fileList: rrr.fileList
               })
             }
           })
          }
        })
      }
    })
  },

php

<?php
    header("Access-Control-Allow-Origin: *"); //解决跨域
    header(&#39;Access-Control-Allow-Methods:GET&#39;);// 响应类型  
    header(&#39;Access-Control-Allow-Headers:*&#39;); // 响应头设置 
    $link=mysql_connect("localhost","root","root"); 
    mysql_select_db("new_test", $link); //选择数据库
    mysql_query("SET NAMES utf8");//解决中文乱码问题
error_reporting(0);
$str = $_GET[&#39;str&#39;];
$file_path="upload/".$str;
if (! file_exists ( $file_path )) {    
header(&#39;HTTP/1.1 404 NOT FOUND&#39;);  
} else {    
//以只读和二进制模式打开文件   
$file = fopen ( $file_path, "rb" ); 
//告诉浏览器这是一个文件流格式的文件    
Header ( "Content-type: application/octet-stream" ); 
//请求范围的度量单位  
Header ( "Accept-Ranges: bytes" );  
//Content-Length是指定包含于请求或响应中数据的字节长度    
Header ( "Accept-Length: " . filesize ( $file_path ) );  
//用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。
Header ( "Content-Disposition: attachment; filename=" . $str );    
//读取文件内容并直接输出到浏览器    
echo fread ( $file, filesize ( $file_path ) );    
fclose ( $file );    
exit ();    
}    
?>

This article introduces how to download files from WeChat applet and process them through back-end PHP. For more related knowledge, please pay attention to the php Chinese website.

Related recommendations:

Introduction to bubbling, dichotomy insertion, quick sort algorithm

Explain how PHP supports breaking Related content of the file download class that you click on to resume the upload

How to filter the html tag attribute class through php

The above is the detailed content of How to download files from WeChat applet through back-end PHP. 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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)