Firefox browser uses JavaScript to upload large file _php instances

Source: Internet
Author: User
Tags base64 message queue win32

This program is the use of 3.x Firefox browser can read the characteristics of local files, to achieve through the XMLHttpRequest upload large file features, and in the process can upload dynamic display upload progress. Slightly modified, and with the server side, you can achieve the extension of breakpoints and many other functions.
This example is mainly to study the characteristics of Firefox file-input node, other client applications, such as Flash, sliverlight, etc., in the implementation of large file upload client, in the data transmission and server-side storage, and this example of the basic line of thought.
Note: The volume of the file appears to have a tipping point, but how much of this critical point has not been confirmed. It is recommended that you do not upload more than 100M files using this method.
The following are client JavaScript code

Copy Code code as follows:



/*


* Firefoxfilesender version 0.0.0.1


* by MK Winnie_mk (a) 126.com


*


* "This program is limited to firefox3.x version, other browsers can run without testing." 】


* "Test passed: FireFox 3.6.8/apache/2.2.11 (Win32) php/5.2.6"


* ******************************************************************************


* This program is the use of 3.x Firefox browser can read the characteristics of local files


* Implementation of large file upload via XMLHttpRequest function


* and dynamically display the upload progress during the upload process


* Slightly modified, and with the server side, you can achieve the extension of breakpoints and many other functions


* This example is mainly to study the characteristics of Firefox file-input node


* Other client applications, such as Flash, sliverlight, etc., in the implementation of client large file upload


* In the data transmission and server-side storage, and this example of the basic line of thought


* Note: File volume seems to have a tipping point, but how much of this critical point has not yet been confirmed. It is recommended that you do not upload more than 100M files using this method.


* ******************************************************************************


*/


function Firefoxfilesender (config) {


var conf = Config | | {};


/*


* Error Message Queue


*/


This.errmsg = [];


/*


* To determine whether the 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 while attempting to send the binary stream directly, instead sending base64 encoded data.


*/


This.data = (This.data = This.f.files[0].getasdataurl ())


. substr (This.data.indexOf (', ') + 1);


This.length = This.data.length;


/*


* Actual size of the file


*/


This.filesize = this.f.files[0].filesize;


/*


* File type


*/


This.contenttype = This.f.files[0].filetype;


}


/*


* Server-side receive address


*/


This.url = Conf.url;


if (!this.url) {


This.errMsg.push (' Error:not set the instance URL to send binary. ');


}


/*


* The size of the packet sent. Default 100KB


*/


This.packagesize = Conf.packagesize | | 102400;


/*


* Each packet size should be 4 multiples, make sure that the server-side conversion base64 encoded correctly.


*/


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 Read location


*/


position:0,


/*


* Data size. The value is the length of the Base64 string.


*/


Length:-1,


/*


* Check error queue, try to trigger onerror event


*/


Checkerror:function () {


if (This.errMsg.length > 0) {


/*


* Trigger 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 () {


/*


* Circular read sent when the server segment is responding normally.


*/


if (xhr.readystate = = 4 && xhr.status = 200) {


/*


* Trigger Onsending Event


*/


if (typeof _.onsending = = ' function ') _.onsending (_, XHR);


/*


* Delay to send the next request, otherwise the server is overburdened


*/


var send = settimeout (function () {


_.send ();


Cleartimeout (send);


send = null;


}, 100);


}


}


return XHR;


},


/*


* Send data


*/


Send:function () {


This.checkerror ();


/*


* Get the data currently being sent


*/


This.currentdata = This.data.substr (this.position, this.packagesize);


/*


* Change postion, simulate data flow shift


*/


This.position + = This.currentData.length;


/*


* If the read string is longer than 0, the data is sent


* Otherwise trigger onsendfinished event


*/


if (This.currentData.length > 0) {


var xhr = This.createsender ();


/*


* Custom header information, notify server-side file related information


* This part can be modified in practical application.


*/


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 Onsendfinished Event


*/


This.onsendfinished (this);


}


},


/*


* Calculate percentage of sent data


*/


Percent:function () {


if (this.length <= 0) return-1;


Return Math.Round ((this.position/this.length) * 10000)/100;


},


Onsendfinished:null,//The event is triggered with local data sent, not completion information returned by the server side.


Onsending:null,


Onerror:null


}

/*


* Upload Button Event


*/


function Send (Fileid) {


var sender = new Firefoxfilesender (


/*


* Upload configuration file


*/


{


/*


* Input file element, can be a DOM node, or it can be a string value of an ID


*/


File:fileid,


/*


* Server-side address to receive uploaded data


*/


URL: ' uploader.php ',


/*


* The size of the packet each time it is sent. Can be changed based on server specifics. IIS6 defaults to 200K


*/


Packagesize: ' 200000 ',


/*


* This event is triggered when an error occurs. This example only determines whether the parameters are complete when initializing, and does not throw errors in the sending process.


*/


Onerror:function (arrmsg) {


Alert (Arrmsg.join (' \ r \ n '));


sender = null;


Delete sender;


},


/*


* The event is triggered during the send process. This example is used primarily to show progress.


*/


Onsending:function (SD, XHR) {


var per = Sd.percent ();


document.getElementById (' message '). InnerHTML = per + '% ';


/*


* The judgment is triggered by the XHR onreadystatechange event at the end of the last send


* If there are no other errors in the transfer process, you can basically determine that the server-side receive completes


*/


if (parseint (per) = = = Alert (' Server-side receive complete ');}


},


/*


* This event is only triggered when "local data send completes".


* Please distinguish between local data send completion and server-side return completion information in both cases


* In this case, there is no response to the server receiving information


* Even if the server side does not receive and save any data


* Just make sure xhr returns readystate = 4 and status = 200


* Send will continue


* How the server side returns the completion information can be customized by changing the code that receives the data page


* And then judge by the value of the Xhr.responsetext.


*/


Onsendfinished:function () {


Alert (' Local data send complete ');


}


}


);


Sender.send ();


}





The following is the server-side PHP code


Copy Code code as follows:



/*


* Get input information


*/


$b = file_get_contents ("Php://input");


/*


* Info


*/


$headers = Getallheaders ();


$fileName = $headers [' #FILE_NAME #];


$contentType = $headers [' #CONTENT_TYPE #];

/*
* Make some judgments and deal with ...
*/

/*
* The following is a simple server-side response to sending data
*-If the data is posted then the output is converted to a binary stream, and the length of the binary stream is base64
*-otherwise output 0
* This is just an example, and in the JS end did not receive this information
* Similarly, you can also write feedback in the header and so on.
* Feedback information to the client
* The main purpose is to determine whether there are other issues in the upload process
* To ensure that uploaded files are complete
*/
if (!empty ($b 64)) {
$stream = Base64_decode ($b 64);
echo strlen ($stream);
/*
* Append write to File
* Modify File Save location here
*/
$file = fopen ('. $fileName, ' a ');
if ($file)
if (fwrite ($file, $stream))
Fclose ($file);
else echo ' 0 ';




Client complete code


Copy Code code as follows:



<! DOCTYPE html>


2 <html>


3 <head>


4 <meta http-equiv= "Content-type" content= "text/html"; Charset=utf-8 ">


5 <title>firefoxfilesender-!! Only for FireFox!! </title>


6 </head>


7


8 <body>


9 <script type= "Text/javascript" >


10/*


One * Firefoxfilesender version 0.0.0.1


* by MK Winnie_mk (a) 126.com


13 *


14 * "This program is limited to firefox3.x version, other browsers can run without testing." 】


15 * "Test through: FireFox 3.6.8/apache/2.2.11 (Win32) php/5.2.6"


16 * *********************************************************************************


17 * This program is the use of 3.x Firefox browser can read the characteristics of local files


18 * Implementation through XMLHttpRequest upload large file function


19 * and dynamically display the upload progress during the upload process


20 * Slightly modified, and with the server side, you can achieve the extension of breakpoints and many other functions


21 * This example is mainly to study the characteristics of Firefox file-input node


22 * Other client applications, such as Flash, sliverlight, etc., in the implementation of client large file upload


23 * In the data transmission and server-side storage, and this example of the basic line of thought


24 * Note: File volume seems to have a tipping point, but this critical point is not yet confirmed. It is recommended that you do not upload more than 100M files using this method.


25 * *********************************************************************************


26 */


function Firefoxfilesender (config) {


var conf = Config | | {};


29/*


30 * error Message Queue


31 */


This.errmsg = [];


33/*


34 * To determine whether the parameters are complete


35 */


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;


41/*


42 * Failed while attempting to send the binary stream directly, instead sending base64 encoded data.


43 */


This.data = (This.data = This.f.files[0].getasdataurl ()). substr (This.data.indexOf (', ') + 1);


This.length = This.data.length;


46/*


47 * Actual size of the file


48 */


This.filesize = this.f.files[0].filesize;


50/*


51 * File Type


52 */


This.contenttype = This.f.files[0].filetype;


54}


55/*


56 * Server-side receive address


57 */


This.url = Conf.url;


!this.url {this.errMsg.push (' error:not set the instance URL to send binary. ')


60/*


61 * Send the packet size. Default 100KB


62 */


This.packagesize = Conf.packagesize | | 102400;


64/*


65 * Each Send packet size should be a multiple of 4, to ensure that the server-side conversion base64 encoded correctly.


66 */


The IF (this.packagesize% 4!= 0) this.packagesize = parseint (THIS.PACKAGESIZE/4) * 4;


68


this.onsendfinished = conf.onsendfinished | | Null


this.onsending = Conf.onsending | | Null


This.onerror = Conf.onerror | | Null


72}


Firefoxfilesender.prototype = {


74/*


75 * Record the currently sent data


76 */


Currentdata:null,


78/*


79 * Record Read location


80 */


Bayi position:0,


82/*


83 * Data size. The value is the length of the Base64 string.


84 */


Length:-1,


86/*


87 * Check error queue, try to trigger onerror event


88 */


Checkerror:function () {


if (This.errMsg.length > 0) {


91/*


92 * Trigger OnError Event


93 */


typeof This.onerror = = ' function ' && this.onerror (this.errmsg);


return;


96}


97},


98/*


99 * Create XMLHttpRequest


100 */


Createsender:function () {


102 var xhr = new XMLHttpRequest ();


Xhr.open (' POST ', This.url, true);


var _ = this;


Xhr.onreadystatechange = function () {


106/*


107 * When the server segment response is normal, then circular read sent.


108 */


109 if (xhr.readystate = = 4 && xhr.status = 200) {


110/*


111 * Trigger Onsending Event


112 */


113 if (typeof _.onsending = = ' function ') _.onsending (_, XHR);


114/*


115 * Delay to send the next request, otherwise the server is overburdened


116 */


117 var send = settimeout (function () {


118 _.send ();


119 cleartimeout (send);


the send = null;


121}, 100);


122}


123}


124 return XHR;


125},


126/*


127 * Send data


128 */


129 Send:function () {


130 This.checkerror ();


131/*


132 * Get the current data to send


133 */


134 This.currentdata = This.data.substr (this.position, this.packagesize);


135/*


136 * Change postion, simulate data flow shift


137 */


138 This.position + = this.currentData.length;


139/*


140 * If the read string length is greater than 0, the data is sent


141 * Otherwise trigger onsendfinished event


142 */


143 if (This.currentData.length > 0) {


144 var xhr = This.createsender ();


145/*


146 * Custom header information, notify server-side file related information


147 * This part can be modified in practical application.


148 */


149 Xhr.setrequestheader (' #FILE_NAME # ', this.filename);


Xhr.setrequestheader (' #FILE_SIZE # ', this.length);


151 Xhr.setrequestheader (' #CONTENT_TYPE # ', This.contenttype);


152


153 Xhr.send (This.currentdata);


154} else if (typeof this.onsendfinished = = ' function ') {


155/*


156 * Trigger Onsendfinished Event


157 */


158 this.onsendfinished (this);


159}


160},


161/*


162 * Calculate percentage of sent data


163 */


164 Percent:function () {


165 if (this.length <= 0) return-1;


166 return Math.Round (this.position/this.length) * 10000)/100;


167},


Onsendfinished:null,//The event is triggered with local data sent, not completion information returned by the server side.


169 Onsending:null,


170 Onerror:null


171}


172


173/*


174 * Upload Button Event


175 */


176 function%3


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.