Interview Question note: Implement Nginx Upload module function upload file.

Source: Internet
Author: User
Tags nginx server

Linux Server Development Assessment topics
————————————————————————————

Build an Nginx server, can complete the file upload function. The main components are:
<1> front-end HTML page for testing the server upload function
<2> nginx Web server, including the file Upload function module, pay attention to configure the configuration file
<3> returns upload successfully information to the front end for files that have been uploaded successfully

After the hands-on set up, according to the above requirements to cut a few pictures, at the same time the front-end HTML page, nginx configuration file, and if needed to use the business logic code (such as Php/java, etc.), sent to me by mail.

Note: The overall problem code is relatively small, designed to test the analysis of problems, fast learning, problem-solving ability.

Analysis (perhaps I am very difficult to understand, but I would like to say that direct practice is the best ...). ):

First, NINGX upload (

1. Install nginx module file (upload): https://www.nginx.com/resources/wiki/modules/upload/, the default nginx must not install this extension module, You can prepare to delete nginx to download a new stable version of the official website, and compile it ...

# Upload form should is submitted to this location Location/upload {# Pass altered request body to this location upload_pass/upload.php;# Store files to this directory# the directory is hashed, subdirectories 0 1 2 3 4 5 6 7 8 9 s Hould exist

Here's a 10-folder dump. Upload_store/usr/share/nginx/html/file 1;# allow uploaded files to is read only by user Uploa D_store_access user:r; It is here that he will give you the name automatically. # Set specified in Request body Upload_set_form_field "${upload_field_name}_name" $upload _file_name; Upload_set_form_field "${upload_field_name}_content_type" $upload _content_type; Upload_set_form_field "${upload_field_name}_path" $upload _tmp_path;# Inform backend about hash and size of a file u Pload_aggregate_form_field "${upload_field_name}_md5" $upload _file_md5; Upload_aggregate_form_field "${upload_field_name}_size" $upload _file_size; Upload_pass_form_field "^submit$|^description$"; }
This is a big pit, because if the default is the current server 80 port, configuration this is going to go wrong, I directly useless agent, directly
        Upload_pass   /upload.php;


#location @test {
#
#}

2.Nginx a route (see my profile below) detects the upload request, will be each of your defined form file name, uploaded to a different folder, altogether 10 (Create 10 folders, named 0 1 2 3 ... ), file location customization (but be sure to include those 10 folders, this remember), it is necessary to detect the folder you create the Nginx has write permissions, this can see log (this is very important), if you want to play a bit of tricks after the configuration, you can play, you can limit the upload speed and so on, And can do forwarding, if you configure the proxy server itself to do the URL reverse proxy, it can certainly be forwarded to upload files to multiple nginx server (upload file submission information, such as the location of the file and so on. ) to drop ...

Second, direct PHP upload

PHP upload files, it is necessary to configure the Nginx module, so many people will confuse, in fact, the two are different,

Normal upload process: HTML submission upload file, Nginx received after throwing to the TMP directory, PHP received, the TMP upload files to the folder you want to put.

-------------------------------------------------------------------

Both need to write HTML, directly to Nginx, in the upload Modules configuration, is able to directly accept a number of file upload, but since the face of the question is called me to achieve a file upload, then I write so much to do! No eggs, anyway.

<!--This is submitted to Nginx--> <input type= "file" Name= "File1" ><BR> 
<input type= "file" Name= "File2" ><br>< /pre>
    <input type= "Submit" name= "Submit" value= "Upload" >    <input type= "hidden" name= "test" value= "value" > </form></body>

  

1: Configure NINGX Install Upload Modules for file upload and accept Ningx post from PHP parameters.

2. Upload files directly from HTML by writing PHP

server {Listen 80;    server_name Localhost;charset Utf-8;access_log/usr/local/nginx/logs/access.log main; Client_max_body_size 100m;# Upload form should be submitted to the location Location/upload {# Pass altered request B Ody to the upload_pass/upload.php;# Store files to this directory# the directory is hashed, Subdirecto Ries 0 1 2 3 4 5 6 7 8 9 should exist Upload_store/usr/share/nginx/html/file 1;# allow uploaded files to be read O Nly by the user upload_store_access user:r;# Set specified fields in request body Upload_set_form_field "${uploa        D_field_name}_name "$upload _file_name;        Upload_set_form_field "${upload_field_name}_content_type" $upload _content_type; Upload_set_form_field "${upload_field_name}_path" $upload _tmp_path;# Inform backend about hash and size of a file u        Pload_aggregate_form_field "${upload_field_name}_md5" $upload _file_md5; Upload_aggregate_form_field "${upload_field_name}_size"$upload _file_size;    Upload_pass_form_field "^submit$|^description$"; } #如果是当前端口, setting proxy_pass error # Pass altered request body to a backend #location @test {# Proxy_pass htpp://127.0.    0.1;        #} location/{root/usr/share/nginx/html/work/public;    Index index.html index.htm index.php;  } error_page 404/404.html;# redirect server error pages to the static page/50x.html Error_page 500    502 503 504/50x.html;    Location =/50x.html {root/usr/share/nginx/html;        } location ~ \.php$ {root/usr/share/nginx/html/work/public;        Fastcgi_pass Unix:/opt/remi/php70/root/run/lock/php-fcgi.sock;        Fastcgi_index index.php;        Fastcgi_param script_filename $document _root$fastcgi_script_name;    Include Fastcgi_params;    } location ~. *\. (gif|jpg|jpeg|png|bmp|swf) $ {expires 15d;    } location ~. *\. (JS|CSS)? $ {Expires 1d; }}

  

I feel ~~~~~

Then paste the PHP code: just the corresponding interview questions, you can not really infertile with my code, out of the matter I don't care, don't look for me ...

<?phpheader (' content-type:text/html;charset=utf-8 ');//File suffix = = File type $type = ['. pdf ' + ' application/pdf '];     Const FILE_DIR = '/usr/share/nginx/html/work/';//If the non-Nginx upload module uploads the file if (count (($file = $_files[' file ')) > 0) { if ($file [' error '] = = 0) {//Determine if the file type exists, the file suffix is our own key to define if ($fileType = Array_search ($file [' type '], $ty            PE) {//Name the directory at the current time $date _dir = date (' y-m-d ');                    If the directory is not created, we create an if (!is_dir (file_dir. $date _dir)) {if (!mkdir (file_dir. $date _dir)) {                Return header (' location:503.html '); }}//file md5+ current UNIX timestamp + a 5-bit random number, if the demand here is frequent also can be in microseconds timestamp $filename = File_dir. $date _dir. ‘/‘ . (Md5_file ($file [' tmp_name ']). Time (). Rand (9999, 99999)).            $fileType;            Generate a new file if (rename ($file [' Tmp_name '], $filename)) {return header (' Location:success.html '); }}} switch ($file[' ERROR ']) {case 1:http_response_code (400);        Exit (' The file size exceeds the server's space size ');            Case 2:http_response_code (400);        Exit (' The size of the file to upload exceeds the browser limit ');            Case 3:http_response_code (400);        Exit (' file is only partially uploaded ');            Case 4:http_response_code (404);        Exit (' No files found to upload ');            Case 5:http_response_code (503);        Exit (' Server temp folder is missing ');            Case 6:http_response_code (503);    Exit (' File write to Temp folder error '); }}//if it is Nginx upload Moduleif (count ($file = $_post) > 0) {//Determine if the file type exists, the file suffix is our own key to define if ($fileType = Array_        Search ($file [' File_content_type '], $type)) {//Name the directory at the current time $date _dir = date (' y-m-d '; time ());                If the directory is not created, we create an if (!is_dir (file_dir. $date _dir)) {if (!mkdir (file_dir. $date _dir)) {            Return header (' location:503.html '); }}//file md5+ current UNIX timestamp + a 5-bit random number, if required here frequently also can be used in microseconds timestamp $filename = File_dir. $date _dir. ‘/‘ . (Md5_file ($file [' File_path ']). Time (). Rand (9999, 99999)).        $fileType;        Generate a new file if (rename ($file [' File_path '], $filename)) {return header (' Location:success.html '); }}}http_response_code; exit (' wrong operation mode! ');

Interview Question note: Implement Nginx Upload module function upload file.

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.