Using Javascript to upload large files in FireFox _ PHP Tutorial

Source: Internet
Author: User
The FireFox browser uses Javascript to upload large files. This program uses the Firefox browser of 3.x to read local files, implement the function of uploading large files through xmlHttPRequest, and dynamically display the upload progress during the upload process. This program uses the Firefox browser of 3.x to read local files, implement the function of uploading large files through xmlHttPRequest, and dynamically display the upload progress during the upload process. You can add modifications and work with the server to implement resumable data transfer and other functions.
In this example, some features of the file-input node of FireFox are studied. Other client applications, such as Flash and Sliverlight, are used to upload large files on the client, in terms of data transmission and server-side storage, the idea is basically the same as that in this example.
Note: The file volume seems to have a critical point, but the critical point is not yet confirmed. We recommend that you do not use this method to upload files larger than MB.
The following is the client javascript code

The code is as follows:


/*
* FireFoxFileSender version 0.0.0.1
* By MK winnie_mk (a) 126.com
*
* [This program is only available in FireFox3.x. Other browsers can run the program .]
* [Tested: FireFox 3.6.8/Apache/2.2.11 (Win32) php/5.2.6]
**************************************** ***************************************
* This program uses the FireFox browser of 3.x to read local files.
* Implement the function of uploading large files through xmlhttpRequest
* The Upload progress is displayed dynamically during the upload process.
* Supports resumable data transfer and other functions by adding modifications and working with the server.
* In this example, some features of the file-input node of FireFox are studied.
* Other client applications, such as Flash and Sliverlight, are used to upload large files on the client.
* Data transmission and server-side storage are basically the same as in this example.
* Note: The file volume seems to have a critical point, but the critical point is unconfirmed. We recommend that you do not use this method to upload files larger than MB.
**************************************** ***************************************
*/
Function FireFoxFileSender (config ){
Var conf = config | {};
/*
* Error Message Queue
*/
This. errMsg = [];
/*
* Determine whether all parameters are complete
*/
This. f = typeof conf. file = 'string '?
Document. getElementById (conf. file): conf. file;
If (! This. f) {this. errMsg. push ('Error: Not set the input file .');}
Else if (this. f. files. length <1) {this. errMsg. push ('Error: Not select a file .');}
Else {
This. fileName = this. f. value;
/*
* Failed to send binary streams directly. use base64 encoding to send data.
*/
This. data = (this. data = this. f. files [0]. getAsDataURL ())
. Substr (this. data. indexOf (',') + 1 );
This. length = this. data. length;
/*
* Actual file size
*/
This. fileSize = this. f. files [0]. fileSize;
/*
* File type
*/
This. contentType = this. f. files [0]. fileType;
}
/*
* Server receiving address
*/
This. url = conf. url;
If (! This. url ){
This. errMsg. push ('Error: Not set the instance url to send binary .');
}
/*
* Size of the sent data packet. 100kb by default
*/
This. packageSize = conf. packageSize | 102400;
/*
* The size of each sent data packet should be a multiple of 4 to ensure that base64 encoding is correct on the server side.
*/
If (this. packageSize % 4! = 0)
This. packageSize = parseInt (this. packageSize/4) * 4;

This. onSendFinished = conf. onSendFinished | null;
This. onSending = conf. onSending | null;
This. onError = conf. onError | null;
}
FireFoxFileSender. prototype = {
/*
* Record the currently sent data
*/
CurrentData: null,
/*
* Record reading location
*/
Position: 0,
/*
* Data size. The value is the length of a base64 string.
*/
Length:-1,
/*
* Check the error queue and try to trigger the onError event.
*/
CheckError: function (){
If (this. errMsg. length> 0 ){
/*
* Trigger the onError event
*/
Typeof this. onError = 'function' & this. onError (this. errMsg );
Return;
}
},
/*
* Create XMLHttpRequest
*/
CreateSender: function (){
Var xhr = new XMLHttpRequest ();
Xhr. open ('post', this. url, true );
Var _ = this;
Xhr. onreadystatechange = function (){
/*
* When the server segment responds normally, it will be read and sent cyclically.
*/
If (xhr. readyState = 4 & xhr. status = 200 ){
/*
* Trigger the onSending event
*/
If (typeof _. onSending = 'function') _. onSending (_, xhr );
/*
* Send the next request in a delayed manner. Otherwise, the server will be overloaded.
*/
Var send = setTimeout (function (){
_. Send ();
ClearTimeout (send );
Send = null;
},100 );
}
}
Return xhr;
},
/*
* Send data
*/
Send: function (){
This. checkError ();
/*
* Get the data to be sent
*/
This. currentData = this. data. substr (this. position, this. packageSize );
/*
* Change postion to simulate data flow shifting
*/
This. position + = this. currentData. length;
/*
* If the length of the read string is greater than 0, the data is sent.
* Otherwise, the onSendFinished event is triggered.
*/
If (this. currentData. length> 0 ){
Var xhr = this. createSender ();
/*
* The Custom header information notifies the server about the file.
* This part can be modified in actual applications.
*/
Xhr. setRequestHeader ('# FILE_NAME #', this. fileName );
Xhr. setRequestHeader ('# FILE_SIZE #', this. length );
Xhr. setRequestHeader ('# CONTENT_TYPE #', this. contentType );

Xhr. send (this. currentData );
} Else if (typeof this. onSendFinished = 'function '){
/*
* Trigger the onSendFinished event
*/
This. onSendFinished (this );
}
},
/*
* Calculate the percentage of sent data
*/
Percent: function (){
If (this. length <= 0) return-1;
Return Math. round (this. position/this. length) * 10000)/100;
},
OnSendFinished: null, // This event is triggered by the completion of local data transmission, not the completion information returned by the server.
OnSending: null,
OnError: null
}

/*
* Upload button event
*/
Function send (fileID ){
Var sender = new FireFoxFileSender (
/*
* Upload the configuration file
*/
{
/*
* The input file element can be a dom node or a string value of id.
*/
File: fileID,
/*
* Server address for receiving uploaded data
*/
Url: 'uploader. php ',
/*
* The size of each sent data packet. It can be changed according to the specific circumstances of the server. IIS6 is 200 KB by default
*/
PackageSize: '000000 ',
/*
* This event is triggered when an error occurs. In this example, the system only checks whether all parameters are complete during initialization and does not throw an error in the sending process.
*/
OnError: function (arrMsg ){
Alert (arrMsg. join ('\ r \ n '));
Sender = null;
Delete sender;
},
/*
* This event is triggered during sending. In this example, the progress is displayed.
*/
OnSending: function (sd, xhr ){
Var per = sd. percent ();
Document. getElementById ('message'). innerHTML = per + '% ';
/*
* This judgment is triggered by the onreadystatechange event of xhr after the last sending is complete.
* If there are no other errors during transmission, you can basically confirm that the server side has completed receiving
*/
If (parseInt (per) = 100) {alert ('server side received successfully ');}
},
/*
* This event is only triggered when the local data transmission is complete.
* Please distinguish between sending completion of local data and sending completion information returned by the server.
* In this example, the server does not respond to any information received by the server.
* Even if the server does not receive or store any data
* Make sure that xhr returns readyState = 4 and status = 200
* Sending continues
* You can customize how the server returns the completion information by changing the code on the receiving data page.
* Determine the xhr. responseText value.
*/
OnSendFinished: function (){
Alert ('Local data transmission completed ');
}
}
);
Sender. send ();
}


The following is the server-side php code

The code is as follows:


/*
* Get input information
*/
$ B64 = file_get_contents ("php: // input ");
/*
* Obtain the header information.
*/
$ Headers = getallheaders ();
$ FileName = $ headers ['# FILE_NAME #'];
$ ContentType = $ headers ['# CONTENT_TYPE #'];

/*
* Make some judgment and processing...
*/

/*
* The following is a simple response from the server to the sent data.
*-If some data is post, the length of the binary stream after base64 is converted to the binary stream
*-Otherwise, the output is 0.
* This is just an example, and the js side does not receive this information.
* Similarly, you can write feedback information in the header.
* Feedback information to the client
* The main purpose is to determine whether other problems occur during the upload process.
* To ensure that the uploaded files are complete
*/
If (! Empty ($ b64 )){
$ Stream = base64_decode ($ b64 );
Echo strlen ($ stream );
/*
* File writing through append
* Modify the file storage location here
*/
$ File = fopen (''. $ fileName, 'A ');
If ($ file)
If (fwrite ($ file, $ stream ))
Fclose ($ file );
} Else echo '0 ';


Complete client code

The code is as follows:



2
3
4
5FireFoxFileSender -!! Only for FireFox !!
6
7
8
9

Related 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.