search
HomeBackend DevelopmentPHP TutorialReprint-Sharing of ThinkPHP file upload class_PHP tutorial

The upload class uses the Net.UpdateFile class in the ORG class library package. The latest version of the upload class includes the following functions (some functions need to be combined with other class libraries in the ThinkPHP system):

1. Basic upload function

2. Support batch upload

3. Support generating image thumbnails

4. Custom parameter upload

5. Upload detection (including size, suffix and type)

6. Support upload type, attachment size, upload path definition

7. Support hash or date subdirectory saving of uploaded files

8. Upload images Security detection

9. Support naming rules for uploaded files

10. Support Hash verification of uploaded files


No special processing is required to use the upload function in ThinkPHP . For example, here is a form submission with attachment upload:

The code is as follows Copy code
 代码如下 复制代码






 代码如下 复制代码
Public function upload(){
import(“ORG.Net.UploadFile”);
$upload = new UploadFile(); // 实例化上传类
$upload->maxSize = 3145728 ; // 设置附件上传大小
$upload->allowExts = array(‘jpg’, ‘gif’, ‘png’, ‘jpeg’); // 设置附件上传类型
$upload->savePath = ‘./Public/Uploads/’; // 设置附件上传目录
if(!$upload->upload()) { // 上传错误 提示错误信息
$this->error($upload->getErrorMsg());
}else{ // 上传成功 获取上传文件信息
$info = $upload->getUploadFileInfo();
}
// 保存表单数据 包括附件数据
$User = M(“User”); // 实例化User对象
$User->create(); // 创建数据对象
$User->photo = $info[0]["savename"]; // 保存上传的照片 根据需要自行组装
$User->add(); // 写入用户数据到数据库
$this->success(“数据保存成功!”);
}

Note Enctype="multipart/form-data" must be added to the Form tag of the form before the file can be uploaded. Because the form is submitted to the upload operation method of the current module, we can add the following upload method in the module class:

The code is as follows Copy code
Public function upload(){
 代码如下 复制代码
import(“ORG.Net.UploadFile”);
$upload = new UploadFile(); // 实例化上传类
import("ORG.Net.UploadFile" );$upload = new UploadFile(); // Instantiate the upload class$upload->maxSize = 3145728; // Set the attachment upload size$upload->allowExts = array(' jpg', 'gif', 'png', 'jpeg'); // Set attachment upload type$upload->savePath = './Public/Uploads/'; // Set attachment upload directory if(!$upload->upload()) { //Upload error prompt error message$this->error($upload->getErrorMsg());}else{ //Upload successful Get uploaded file information$info = $upload->getUploadFileInfo();}// Save form data including attachment data$User = M(“User”); // Example Convert User object $User->create(); // Create data object $User->photo = $info[0]["savename"]; // Save uploaded photos as needed Assembly$User->add(); // Write user data to the database$this->success("Data saved successfully! ”);}
First, instantiate the upload class
The code is as follows Copy code
import(“ORG.Net .UploadFile”);$upload = new UploadFile(); // Instantiate the upload class

After instantiating the upload class, you can set some upload attributes (parameters). The supported attributes are:

maxSize: The maximum file size for file upload (in bytes) Unit) Default is -1, no size limit

savePath: File saving path, if left blank, the path defined by the UPLOAD_PATH constant will be taken

saveRule: Save rule for uploaded files, must be a without any The function name of the parameter, for example, can be time, uniqid com_create_guid, etc., but it must be able to ensure that the generated file name is unique. The default is uniqid

hashType: Hash verification method for uploaded files, the default is md5_file

autoCheck: whether to automatically detect attachments, the default is automatic detection

uploadReplace: whether a file with the same name is overwritten

allowExts: file suffix allowed to be uploaded (leave blank to not limit), Use array settings, the default is an empty array

allowTypes: File types allowed to be uploaded (leave blank to not limit), use array settings, the default is an empty array

thumb: Whether image files need to be uploaded Perform thumbnail processing, the default is false

thumbMaxWidth: The maximum width of thumbnails, multiples are separated by commas

thumbMaxHeight: The maximum height of thumbnails, multiples are separated by commas

thumbPrefix: The file prefix of the thumbnail, the default is thumb_ (If you set multiple thumbnail sizes, please set multiple prefixes here)

thumbSuffix: The file suffix of the thumbnail, the default is empty (If you set multiple thumbnail sizes, please set multiple suffixes here)

thumbPath: The saving path of the thumbnail. If left blank, take the file upload directory itself

thumbFile: Specify the file name of the thumbnail

thumbRemoveOrigin: whether to delete the original image after generating the thumbnail

autoSub: whether to use a subdirectory to save the uploaded file

subType: subdirectory creation method, The default is hash, which can be set to hash or date

dateFormat: Specify the date format when the subdirectory mode is date

hashLevel: The level at which the subdirectory is saved, the default is one level

The above attributes can be set directly, for example:

 代码如下 复制代码
$upload->thumb = true
$upload->thumbMaxWidth = “50,200″
$upload->thumbMaxHeight = “50,200″

The function of generating thumbnails requires the support of the Image class.

After setting the upload parameters, you can call the upload method of the UploadFile class to upload the attachment. If it fails, return false and use the getErrorMsg method to obtain the error message; if the upload is successful, you can obtain it by calling the getUploadFileInfo method. List of successfully uploaded attachment information. Therefore, the return value of the getUploadFileInfo method is an array, each element of which is the uploaded attachment information. Each attachment information is an array that records the following information, including:

key: the name of the form for uploading the attachment

savepath: the save path of the uploaded file

name: The original name of the uploaded file

savename: the saved name of the uploaded file

size: the size of the uploaded file

type: the MIME type of the uploaded file

extension : The suffix type of the uploaded file

hash: The hash verification string of the uploaded file

After the file is successfully uploaded, you can use these attachment information to perform other data access operations, such as saving Either to the current data table or to a separate attachment data table.

If you need to upload multiple files, you only need to modify the form and add the

XML/HTML code

 代码如下 复制代码

Change to

XML/HTML code



The file upload class of both methods of multi-attachment upload system can be automatically recognized. http://www.bkjia.com/PHPjc/444697.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/444697.htmlTechArticleThe upload class uses the Net.UpdateFile class in the ORG class library package. The latest version of the upload class includes the following functions ( Some functions need to be combined with other class libraries of the ThinkPHP system): 1. Basic upload function 2...
The code is as follows
 代码如下 复制代码



或者

PHP代码


Copy code

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft