Home php教程 php手册 PHP jQuery ajax无刷新文件下载次数统计

PHP jQuery ajax无刷新文件下载次数统计

May 25, 2016 pm 04:55 PM
iconv select Download Document

本文章基于php + mysql +jquery的ajax来实现无刷新文件下载次数统计,有需要的朋友可参考,下面我一步步给大家详细介绍实现过程。

本实例需要读者具备PHP、Mysql、jQuery以及html、css等相关的基本知识,在开发示例前,需要准备Mysql数据表,本文假设有一张文件下载表downloads,用来记录文件名、保存在文件服务器上的文件名以及下载次数。前提是假设下载表中已存在数据,这些数据可能来自项目中的后台上传文件时插入的,以便我们在页面中读取。downloads表结构如下:

 代码如下 复制代码

CREATE TABLE IF NOT EXISTS `downloads` ( 
  `id` int(6) unsigned NOT NULL AUTO_INCREMENT, 
  `filename` varchar(50) NOT NULL, 
  `savename` varchar(50) NOT NULL, 
  `downloads` int(10) unsigned NOT NULL DEFAULT '1', 
  PRIMARY KEY (`id`), 
  UNIQUE KEY `filename` (`filename`) 
) ENGINE=MyISAM  DEFAULT CHARSET=utf8; 

您也可以直接下载Demo,导入SQL文件,数据都有了。

HTML

我们在index.html页面body中加入如下HTML结构,其中ul.filelist用来陈列文件列表,现在它里面没有内容,我们将使用jQuery来异步读取文件列表,所以别忘了,我们还需要在html中加载jQuery库文件。

 代码如下 复制代码

 
    
     
        
 
 

CSS

为了让demo更好的展示页面效果,我们使用CSS来修饰页面,以下的代码主要设置文件列表展示效果,当然实际项目中可以根据需要设置相应的样式。

 代码如下 复制代码

#demo{width:728px;margin:50px auto;padding:10px;border:1px solid #ddd;background-color:#eee;} 
ul.filelist li{background:url(http://pic1.phprm.com/2013/05/02/bg_gradient.jpg) repeat-x center bottom #F5F5F5; 
border:1px solid #ddd;border-top-color:#fff;list-style:none;position:relative;} 
ul.filelist li.load{background:url(http://pic1.phprm.com/2013/05/02/ajax_load.jpg) no-repeat; padding-left:20px;  
border:none; position:relative; left:150px; top:30px; width:200px} 
ul.filelist li a{display:block;padding:8px;} 
ul.filelist li a:hover .download{display:block;} 
span.download{background-color:#64b126;border:1px solid #4e9416;color:white; 
display:none;font-size:12px;padding:2px 4px;position:absolute;right:8px; 
text-decoration:none;text-shadow:0 0 1px #315d0d;top:6px; 
-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;} 
span.downcount{color:#999;padding:5px;position:absolute; margin-left:10px;text-decoration:none;} 

PHP

为了更好的理解,我们分两个PHP文件,一个是filelist.php,用来读取mysql数据表中的数据,并输出为JSON格式的数据用来给前台index.html页面调用,另一个是download.php,用来响应下载动作,更新对应文件的下载次数,并且通过浏览器完成下载。其实还有一个数据库连接文件conn.php,已经打包在下载压缩包里了,点击这里下载。

filelist.php读取downloads表,并通过json_encode()将数据以JSON格式输出,这样是为下面的Ajax异步操作准备的。

 代码如下 复制代码

require 'conn.php'; //连接数据库 
$result = mysql_query("SELECT * FROM downloads"); 
if(mysql_num_rows($result)){ 
    while($row=mysql_fetch_assoc($result)){ 
        $data[] = array( 
            'id' => $row['id'], 
            'file' => $row['filename'], 
            'downloads'=> $row['downloads'] 
        ); 
    } 
    echo json_encode($data); 

 

download.php根据url传参,查询得到对应的数据,检测要下载的文件是否存在,如果存在,则更新对应数据的下载次数+1,并且使用header()实现下载功能。值得一提的是,使用header()函数,强制下载文件,并且可以设置下载后保存到本地的文件名称。一般情况下,我们通过后台上传程序会将上传的文件重命名后保存到服务器上,常见的有以日期时间命名的文件,这样的好处之一就是避免了文件名重复和中文名称乱码的情况。而我们下载到本地的文件可以使用header("Content-Disposition: attachment; filename=" .$filename )将文件名设置为易于识别的文件名称。

 代码如下 复制代码

require('conn.php');//连接数据库 
$id = (int)$_GET['id']; 
 
if(!isset($id) || $id==0) die('参数错误!'); 
$query = mysql_query("select * from downloads where id='$id'"); 
$row = mysql_fetch_array($query); 
if(!$row) exit; 
$filename = iconv('UTF-8','GBK',$row['filename']);//中文名称注意转换编码 
$savename = $row['savename']; //实际在服务器上的保存名称 
$myfile = 'file/'.$savename; 
if(file_exists($myfile)){//如果文件存在 
    //更新下载次数 
    mysql_query("update downloads set downloads=downloads+1 where id='$id'"); 
    //下载文件 
    header("Content-type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=" .$filename ); 
    exit; 
}else{ 
    echo '文件不存在!'; 

 

jQuery

前端页面jQuery主要完成两个任务,一是通过Ajax异步读取文件列表并展示,二是响应用户点击事件,将对应的文件下载次数+1,来看代码:

 代码如下 复制代码

$(function(){ 
    $.ajax({ //异步请求 
        type: 'GET', 
        url: 'filelist.php', 
        dataType: 'json', 
        cache: false, 
        beforeSend: function(){ 
            $(".filelist").html("

  • 正在载入...
  • "); 
            }, 
            success: function(json){ 
                if(json){ 
                    var li = ''; 
                    $.each(json,function(index,array){ 
                        li = li + '
  • '+array['file']+ 
    ''+array['downloads']+' 
    点击下载
  • '; 
                    }); 
                    $(".filelist").html(li); 
                } 
            } 
        }); 
        $('ul.filelist a').live('click',function(){ 
            var count = $('.downcount',this); 
            count.text( parseInt(count.text())+1); //下载次数+1 
        }); 
    }); 

     

    首先,页面载入完后,通过$.ajax()向后台filelist.php发送一个GET形式的Ajax请求,当filelist.php相应成功后,接收返回的json数据,通过$.each()遍历json数据对象,构造html字符串,并将最终得到的字符串加入到ul.filelist中,形成了demo中的文件列表。

    然后,当点击文件下载时,通过live()响应动态加入的列表元素的click事件,将下载次数进行累加



    本文地址:

    转载随意,但请附上文章地址:-)

    Statement of this Website
    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

    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)
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Python opening operation after downloading the file Python opening operation after downloading the file Apr 03, 2024 pm 03:39 PM

    Python provides the following options to open downloaded files: open() function: open the file using the specified path and mode (such as 'r', 'w', 'a'). Requests library: Use its download() method to automatically assign a name and open the file directly. Pathlib library: Use write_bytes() and read_text() methods to write and read file contents.

    Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

    To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

    How to use PHP functions to upload and download attachments for sending and receiving emails? How to use PHP functions to upload and download attachments for sending and receiving emails? Jul 25, 2023 pm 08:17 PM

    How to use PHP functions to upload and download attachments for sending and receiving emails? With the rapid development of modern communication technology, email has become an important way for people to communicate and transmit information in daily life. In web development, we often encounter the need to send and receive emails with attachments. As a powerful server-side scripting language, PHP provides a wealth of functions and class libraries that can simplify the email processing process. This article will introduce how to use PHP functions to upload and download attachments for sending and receiving emails. Email is sent first, we

    How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

    How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

    How to use Hyperf framework for file downloading How to use Hyperf framework for file downloading Oct 21, 2023 am 08:23 AM

    How to use the Hyperf framework for file downloading Introduction: File downloading is a common requirement when developing web applications using the Hyperf framework. This article will introduce how to use the Hyperf framework for file downloading, including specific code examples. 1. Preparation Before starting, make sure you have installed the Hyperf framework and successfully created a Hyperf application. 2. Create a file download controller First, we need to create a controller to handle file download requests. Open the terminal and enter

    How to trigger file download when clicking HTML button or JavaScript? How to trigger file download when clicking HTML button or JavaScript? Sep 12, 2023 pm 12:49 PM

    Nowadays, many applications allow users to upload and download files. For example, plagiarism detection tools allow users to upload a document file that contains some text. It then checks for plagiarism and generates a report that users can download. Everyone knows how to use inputtypefile to create a file upload button, but few developers know how to use JavaScript/JQuery to create a file download button. This tutorial will teach you various ways to trigger a file download when an HTML button or JavaScript is clicked. Use HTML's <a> tag and download attribute to trigger file download when the button is clicked. Whenever we give the <a> tag

    Recommended essential functions for Chinese processing: Detailed explanation of PHP iconv function Recommended essential functions for Chinese processing: Detailed explanation of PHP iconv function Jun 27, 2023 pm 02:04 PM

    In the process of text processing, it is a common requirement to convert strings in different encoding formats. The iconv (InternationalizationConversion) function provided in the PHP language can meet this need very conveniently. This article will introduce the use of iconv function in detail from the following aspects: Definition of iconv function and introduction to common parameters Example demonstration: Convert GBK encoded string to UTF-8 encoded string Example demonstration: Convert UTF

    Asynchronous processing method of Select Channels Go concurrent programming using golang Asynchronous processing method of Select Channels Go concurrent programming using golang Sep 28, 2023 pm 05:27 PM

    Asynchronous processing method of SelectChannelsGo concurrent programming using golang Introduction: Concurrent programming is an important area in modern software development, which can effectively improve the performance and responsiveness of applications. In the Go language, concurrent programming can be implemented simply and efficiently using Channels and Select statements. This article will introduce how to use golang for asynchronous processing methods of SelectChannelsGo concurrent programming, and provide specific

    See all articles