Recently made a product that needs to be implemented from the Web page to upload files to the server. In general, the use of Ajax asynchronous way, create an IFRAME, in the IFRAME to the data form to the backend server script, by the server script (such as PHP) to receive uploaded data. This approach has a performance and efficiency problem. Therefore, the decision to use Nginx upload module to complete the function of receiving data, after receiving the data, then to the back-end scripting language for subsequent processing (such as: Mobile files, insert the file information into the database). At the same time, due to the need to display the upload in front of the progress, so you can use Nginx a uploadprogress module to obtain.
The entire process block diagram is as follows:
Implementation steps:
1, to see if nginx installed these two modules (Nginx_upload_module and nginx_uploadprogress_module), command nginx-v (note is uppercase), you can view the Nginx at the time of the compile parameters, If the above two modules are found, the Nginx has installed these two modules. If not, you will need to install these two nginx modules. Since these two modules are not in the Nginx source code, you will need to recompile the nginx, and in the compilation option add
--add-module=/Module Source code path/nginx_upload_module-2.2.0--add-module=/Module source code path/nginx_uploadprogress_module-0.8.2.
2, because the front-end use of the product is the jquery framework, so, find a ready-made jquery under the upload file plugin (ajaxfileupload). The basic principle of the code is to create an IFRAME dynamically, add a form in the IFRAME, the final data put in this form to the server, the amount of code is small also 200来 line code. The front end code is as follows:
<script type= "Text/javascript" src= "Http://192.168.1.203:7100/js/libs/ajaxfileupload.js"
></script> <script type= "Text/javascript" > Function UploadFile () {$.ajaxfileupload ({ URL: ' http://192.168.1.203:7100/upload/',//uploaded address Sercureuri:false, Fileelementid: ' Filetou Pload ', DataType: ' JSON ', Success:function (data,status) {if (typeof (Data.error)!= '
Undefined ') {if (Data.error!= ') alert (data.error);
else{alert (data.msg);
}, Error:function (Data,status, E) {alert (e);
}
});
return false; } </script> <div> <input type= "file" Name= "AddFile" size= "id=" Filetoupload "/>" <input type= "bu Tton "value=" Upload "onclick=" return UploadFile (); /> </div>
Where the success callback function argument is the result of the server being returned to the browser.
3, configure Nginx, upload the module to receive the page upload file. Add the following configuration to the Nginx configuration file and note that it is added to the server context.
Location =/upload {
upload_pass/service.php?path=uploadfile&a=upload_server;//indicates that the Nginx received the uploaded file and then handed it to the backend address
Upload_cleanup 400 404 499 500-505; Indicates that when these HTTP status codes occur, the uploaded files will be deleted
Upload_store/tmp/upload_tmp 1;//Upload module received the file temporary storage path, 1 means, the way is required under/tmp/upload_tmp to create a directory name of 0 to 9 directory, upload will be a hash processing.
Upload_store_access user:r; Specify access Mode
Upload_limit_rate 128k; Set upload speed limit
Upload_set_form_field "${upload_field_name}_name" $upload _file_name; Set the variables for subsequent scripting language access, where ${upload_field_name} controls This example is AddFile. For example, backstage PHP can be $_post[' addfile_name ' to get the name of the uploaded file.
Upload_set_form_field "${upload_field_name}_content_type" $upload _content_type;//ditto
Upload_set_form_field "${upload_field_name}_path" $upload _tmp_path;//because the temporary file storage root path is set in Upload_store, The path is after the split after the upload file has a real path, such as post-processing can be based on this value to upload files copied or moved to the specified directory.
Upload_pass_form_field "^.*$";/
Upload_pass_args on;//opens the switch, which means that the parameters requested by the front-end script are passed to the back-end scripting language, for example: Http://192.168.1.203:7100/upload/?k=23.PHP scripts can be passed through $_post[' K '] to visit.
}
4, the above configuration is over, you can realize the upload function. However, to get the progress of the upload, it is necessary to configure another module nginx_uploadprogress_module. In fact, the principle of getting the current progress is relatively simple, that is, through JavaScript asynchronously to a specific address to send requests, the module will be in JSON format to return the progress of the upload. Configuration is relatively simple.
1, first open this module function, in the Nginx configuration file in the HTTP context, add upload_progress proxied 5m; Where the proxied represents the name (Zone_name Official document), 5m means that each link holds the size of the trace information. In addition, the return format is set to Json,upload_progress_json_output;
2), add a configuration item track_uploads proxied 30s in the above location =/upload; Among them, proxied is just in the first step set the name, 30s means that each link after processing, the link will remain 30s.
3), set up a location to handle JavaScript send request.
Location ^~/progress {
Report_uploads proxied; #GET此地址得到上传进度
}
4), there is also a parameter to consider setting Upload_progress_header, this value defaults to X-progress-id. A bit like SessionID, mainly used in the foreground need to upload files when you need to set this parameter value, such as set to the UUID value. So javascript each send a request to get upload progress time, all need to take this parameter, so upload progress tracking module to know is to return that link progress.
After these three steps, the upload Progress tracking module is configured well. You need to modify the front script right now.
5, modify the 2nd step of the foreground script
<script type= "Text/javascript" src= "Http://192.168.1.203:7100/js/libs/ajaxfileupload.js" ></script> <script type= "Text/javascript" >var interval = undefined;function UploadFile () {var uuid = "";
for (var i = 0; i < i++) {uuid = Math.floor (Math.random () *16). toString (16); } $.ajaxfileupload ({url: ' http://192.168.1.203:7100/upload/? X-progress-id= ' + UUID,//uploaded address Sercureuri:false, Fileelementid: ' Filetoupload ', DataType: ' JSON ', Success:function (data,status) {if (typeof (Data.error)!= ' undefined ') {if (Data.error!=
"") alert (data.error);
else{alert (data.msg);
}, Error:function (Data,status, E) {alert (e); }
});interval = window.setinterval (function () {getuploadprogress (UUID); };return false; }function getuploadprogress (UUID) {etajax.sendrequest (' http://192.168.1.203:7100/progress/', ' get ', ' x-progress -id= "+ uuid,getuploadprogresscallback); function Getuploadprogresscallback (type, JSON, HTTP) {if (type = = "Load") {var bar = Document.get Elementbyid (' TP '); if (json.state = = "uploading") {var w = Math.floor (json.received * 100.0/json.size); bar.innerhtml = w + "%"; }/* We are done, stop the interval */if (json.state = ' done ') {Bar.innerh TML = "100%"; Window.cleartimeout (interval); } } } </script> <div> <input type= "file" Name= "AddFile" size= "id=" Filetoupload "/> <input" type= " Button "value=" Upload "onclick=" return UploadFile (); /> </div><div> <div id= "TP" >0%</div> </div>
The bold is the added code, in which some functions call the product encapsulated function, so don't copy it all. The main is to grasp the following points on it:
1, when uploading files need to add a UUID, the corresponding parameter is Upload_progress_header set, the default is X-progress-id.
2, in the request to get the progress of the time, must take this UUID.
3, set a fixed period of time to send asynchronous get-way requests, to obtain progress data.
4, the return of the JSON format is {"state": "Uploading", "size": 3232, "received": 34}, which uploaded the state value is done, if the error occurs, state is error, and will return to status , error encoding.
The steps are introduced here. In addition, JavaScript upload files, when users upload files, it is best to get the upload file size, so you can tell the user in advance whether the size of the allowed upload value. However, there is a problem with the current JavaScript way to get the file size to be compatible with all browsers. I intend to write a flash, through the flash way to get, more insurance.