This article introduces how to upload files. It is refreshing to use php iframe to upload files. If you need it, refer to the following.
First, ajax was unable to upload files, which misled me for a while. If I couldn't sleep tonight, I followed the instructions to upload a new file without refreshing.
In fact, the principle is very simple
| The Code is as follows: |
Copy code |
<Form enctype = "multipart/form-data" method = "POST" target = "upload" action = "http: // localhost/class. upload. php"> <Input type = "file" name = "uploadfile"/> <Input type = "submit"/> </Form> <Iframe name = "upload" style = "display: none"> </iframe> |
Compared with a general <form> tag, a target attribute is used to specify where the tab is opened and data is submitted.
If this attribute is not set, the url in the action will be redirected on this page as usual.
If it is set to the name value of iframe, that is, "upload", it will be opened in the iframe, because CSS is set to hidden, so there will be no movement. If you remove display: none, the returned information of the server is displayed.
In addition, paste your own classes.
| The Code is as follows: |
Copy code |
Class upload { Public $ _ file; Public function _ construct ($ name = null) { If (is_null ($ name) |! Isset ($ _ FILES [$ name]) $ Name = key ($ _ FILES );
If (! Isset ($ _ FILES [$ name]) Throw new Exception ("no file is uploaded ");
$ This-> _ file =$ _ FILES [$ name];
If (! Is_uploaded_file ($ this-> _ file ['tmp _ name']) Throw new Exception ("Exception "); If ($ this-> _ file ['error']! = 0) Throw new Exception ("error code:". $ this-> _ file ['error']); } Public function moveTo ($ new_dir) { $ Real_dir = $ this-> checkDir ($ new_dir ); Return move_uploaded_file ($ this-> _ file ['tmp _ name'], $ real_dir. '/'. $ this-> _ file ['name']); } Private function checkDir ($ dir) { $ Real_dir = realpath ($ dir ); If ($ real_dir = false) Throw new Exception ("the specified directory {$ dir} does not exist "); If (! Is_writable ($ real_dir )) Throw new Exception ("the specified directory {$ dir} cannot be written "); Return $ real_dir; } } |
Call example:
| The Code is as follows: |
Copy code |
$ InputName = 'uploadfile '; // That is, the name value in <input type = "file" name = "uploadfile"/>. this parameter is optional. $ Upload = new upload ($ inputName ); $ New_dir = "/www"; // path to which the object is moved $ Upload-> moveTo ($ new_dir ); |