File upload tips/backend processing "PHP article"

Source: Internet
Author: User

Quote: In the previous article, you can make your upload page look beautiful in a hidden way on the page. But for performance, there is no egg to use, then in the background of processing, there is no processing skills? The so-called backstage skills, should include uploading faster, upload a larger file! So, this article to say, back-end processing are some of the tricks it!

Business Scenario One, we will only choose a single file upload, and do not need to do some real-time verification work. Well, maybe there is no optimization to say, because, finally you have to do, just put this file in the table dropdowns the last to submit, direct processing can!

Business Scenario Two, you need to upload multiple files, and always need to verify the contents of the file, and the corresponding page display. In this case, after the user has chosen to upload the file, we need to upload the file immediately, because we need to read the information in the file, at the time of the final submission, we also need to submit a file. Obviously, here is the existence of a duplicate upload work, a time consuming user, two is the consumption of server bandwidth resources! Optimization, can be expected to the method is also very simple, can not be in the first upload after the file, the file remains in the server, the actual submission of the form, to read this has been uploaded temporary files can be. Yes, this is our approach!

Business Scenario III, similar to scenario two, requires uploading multiple files, but multiple files may be uploaded separately. That is, we may upload the first 10M, the second upload of 10M, a total of 10 uploads, then, on the server side, a one-time commit is definitely beyond the upload size limit, but if we are divided into each upload, it is possible, and the last time to submit, We just need to pass the short text message up!

The idea is really simple, it seems, there is no problem, but, maybe I was limited ability, it took me a lot of time to deal with this what the ghost! Below, I will give some sample code for reference:

File upload Technique (a single uploaded file as a temporary file exists on the server side) sample code:

1. Page JS processing

        //Click to select the finished file, trigger the upload file operation, upload the file to the server temp directory$ ('. Upload-real-file '). Off (). On (' Change ',function(){            if(!$( This). Val ()) {return false; }            varResponseobjid = $ ( This). attr (' Response-id '); varResponseobj = $ (' # ' +Responseobjid); $(' #Form '). Ajaxsubmit ({URL:'/aa/bb/uploadtmpapktool ', Resetform:false, DataType:' JSON ', Beforesubmit:function(option) {window.loading= Layer.load (2); }, Success:function(data, statustext) {layer.close (window.loading); if(Data.status = = 1) {responseobj.html (data.apkinfohtml); varParentcontainer =Responseobj.parent (). Parent (), Namecontainer= Parentcontainer.find ('. File-name-container '));                        Namecontainer.html (Data.apkname); Namecontainer.attr (' Title ', Data.apkname); Responseobj.find ('. File-tmp '). HTML (data.fileinfo);//Store file information in a hidden domain so that it can be found at commit time$ (Submitid). Removeattr (' disabled '); }Else{Layer.alert (data.info); }}, Error:function(data) {layer.close (window.loading); Layer.alert (' Unknown error, please try again later! ‘);            }            }); return false;//prevents dialog from turning off automatically});

2. Obviously, the page needs to get the file information, background processing code (PHP)

        $apkConfig=$this-_getapkconfig (); $params=$this->getfilteredparam (' Get '); $subFile=$_files[' Apktoolfiles ']; $apkName=$apkInfoHtml= ""; if(Empty($subFile))        {            $this->ajaxreturn (Array(' status ' = -4, ' info ' = ' Please select files to upload ')); }        foreach($subFile[' Name '] as $subKey=$subVal)        {            if($subFile[' Name '] [$subKey])            {                $fileData=$this->_getfiledata ($subFile,$subKey); $checkData=Array(                    ' MaxSize ' =$apkConfig[' File_max_size '], ' savepath ' =$apkConfig[' Tmp_child_path '], ' extarr ' =Array(' apk '), ' releasename ' =Str_replace('. apk ', ',$fileData[' FileName ']),//Unique                ); $checkResult=$this->_checkfiledata ($fileData,$checkData); if($checkResult[' status ']! = 1)                {                    $this->ajaxreturn ($checkResult); }                //Moving Files                $filePath=$checkData[' Savepath ']. ‘/‘ .$fileData[' FileName ']. '. tmp '. GENRANDSTR (6);; $this->_moveuploadedfile ($fileData[' Tmpname '],$filePath); $apkInfo=$this->_apkparser ($filePath);//parsing                if($apkInfo[' Umeng_channel ']! = ' Umeng_channel_value ')                {                    @unlink($filePath);//Delete invalid file                    $this->ajaxreturn (Array(' status ' = 0, ' info ' = ' umeng_channel ' value if Umeng_channel_value.)); }                $TMPFILEARR[' file_info '] =Array(                    ' Name ' + =$subFile[' Name '] [$subKey], ' type ' = =$subFile[' type '] [$subKey], ' tmp_name ' =Str_replace($apkConfig[' Tmp_child_path ']. ‘/‘, ‘‘,$filePath), ' ERROR ' =$subFile[' ERROR '] [$subKey], ' size ' =$subFile[' Size '] [$subKey],                ); //dump this value and no longer upload files repeatedly            }            Else            {                $this->ajaxreturn (Array(' status ' = 0, ' info ' = ' file cannot be empty ')); }            foreach($apkInfo  as $key=$val)            {                $apkInfoHtml.= "{$key}:{$val} \ r \ n "; }            $apkName=$fileData[' FileName ']; $version=$apkInfo[' Versionname ']; }        $fileInfo=Htmlspecialchars(Json_encode ($TMPFILEARR[' File_info '])); $fileInfoHtml= "<input name=\" apktoolfiletmp[]\ "Value= ' {$fileInfo} ' type=\ ' hidden\ "/>";//Be sure to use htmlspecialchars before outputting, otherwise the page value will not display correctly and get to the correct file information        $this->ajaxreturn (Array(' status ' = 1, ' info ' = ' upload successful ', ' version ' =$version, ' Item ' =$item, ' apkname ' =$apkName, ' apkinfohtml ' =$apkInfoHtml, ' fileInfo ' =$fileInfoHtml)); }

3. By two parts of the code, we already have the correct information on the page, only need to submit the form at the end of the time, do not submit the file to the server, in the server-side processing, only the temporary files uploaded before the location can be moved , so even if it is done!

$ ('. Upload-file-real '). attr (' disabled ', ' disabled ');        // disable uploading a file before submitting the form

4. Follow-up work

After uploading the temporary file to the server, it is not possible to determine whether the user canceled the current operation, if canceled, the temporary file will always exist in the server, so we need a scheduled cleanup temporary directory script. Of course, this is very simple, just need to find this directory, compare the time, such as more than a day before the file is deleted. Pay attention to control the frequency of cleaning!

5. Off-Topic

The log is really important, where the error, where to delete files, where to clean up the database, must do a good record, otherwise, to find the reason, where to shout for help!

  

Upload files to the server temp directory, the back-end processing principle looks very simple, but also need you to carefully debug, at least when I was doing this small function, it really cost a lot of strength to clear!

File upload tips/backend processing "PHP article"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.