search
HomeBackend DevelopmentPHP TutorialHow to use Thinkphp5+uploadify to upload files

This time I will show you how to use Thinkphp5 uploadify to implement file upload, what are the precautions for using Thinkphp5 uploadify to implement file upload, the following is a practical case, let’s take a look .

It was my first time to come into contact with server-side development. I tried to make an OTA backend server while learning, and it took a lot of effort to achieve file uploading and progress bar display.

Encountered several problems:

1. Large file upload failed
2.Upload canceled X matches cannot be displayed
3. I don’t know how Pass the variable value to the background php

Record the process:

1. Download the uploadify code to the project, such as public\plug-ins\uploadify Down.
2. The front-end script is as follows.

The client passes the version number in formData. Please see the version_id assignment method. You need to assign it in the controller first.

Cancel matching cannot be displayed, you need to modify the background: url('uploadify-cancel.png') in uploadify.css

Pay attention to the writing of uploader in uploadify


  
<script> <?php $timestamp = time();?> var maxSize = 1024 * 1024*1024;//1G $(function() { $(&#39;#uploadify&#39;).uploadify({ &#39;debug&#39; : false, <span style="white-space:pre"> &#39;fileSizeLimit &#39;: maxSize, &#39;formData&#39; : { &#39;timestamp&#39; : &#39;<?php echo $timestamp;?>&#39;, &#39;token&#39; : &#39;<?php echo md5(&#39;unique_salt&#39; . $timestamp);?>&#39;, <span style="white-space:pre"> &#39;version_id&#39;: "{$version_id}" }, &#39;swf&#39; : &#39;/public/plug-ins/uploadify/uploadify.swf&#39;, <span style="white-space:pre"> &#39;cancelImg&#39;:&#39;/public/plug-ins/uploadify/uploadify-cancel.png&#39;, &#39;uploader&#39; : &#39;{:url("Package/upload")}&#39;, <span style="white-space:pre"> &#39;fileTypeDesc&#39; : &#39;zip文件&#39;, <span style="white-space:pre"> &#39;fileTypeExts&#39; : &#39;*.zip&#39;, <span style="white-space:pre"> &#39;multi&#39;: false }); }); </script>

3. The back-end script corresponds to the upload function of the controller Package

Pay attention to the method of obtaining the uploaded file. You cannot use the method of obtaining the official Thinkphp5 document.

The saved file name cannot contain special symbols

Modify php.ini: upload_max_filesize = 1024M post_max_size=48 Restart the service

public function upload(){
  $verifyToken = md5('unique_salt' . $_POST['timestamp']);
  if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
  $tempFile = $_FILES['Filedata']['tmp_name'];
    /*
    $targetFolder = '/public/uploads'; // Relative to the root
  $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
  $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
  // Validate the file type
  $fileTypes = array('jpg','jpeg','gif','png','zip'); // File extensions
  $fileParts = pathinfo($_FILES['Filedata']['name']);
  if (in_array($fileParts['extension'],$fileTypes)) {
    move_uploaded_file($tempFile,$targetFile);
    echo '1';
  } else {
    echo 'Invalid file type.';
  }*/
    $version = model("Version")->retrieve_by_version($_POST['version_id']);
    if($version){
      $file = new File($tempFile,'rw');
      $hash_code = $file->hash();
      $time = date("Y-m-d-i-s",$_POST['timestamp']);
      $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.$version['project_name'].DS.$version['version_name'],'update_'.$time.'.zip');
      if($info){
        // 成功上传后 获取上传信息
        echo $info->getExtension();
        echo $info->getSaveName();
        echo $info->getFilename();
      }else{
        // 上传失败获取错误信息
        echo $file->getError();
      }
    }else{
      echo '找不到对应版本';
    }
  }
}

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to dynamically add, modify, and delete JS arrays and JSON objects

How to use JS Inheritance and multiple inheritance

The above is the detailed content of How to use Thinkphp5+uploadify to upload files. 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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

SecLists

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor