Nginx+Lua 搭建文件服務器

下面詳細的介紹前面第三種方式的搭建:


一:先上圖,

前端界面

二:跳轉頁面

三:功能介紹

    網上有很多使用Nginx搭建文件服務器的教程,我都看了,只能實現基本的功能,因爲Nginx本身就支持文件的上傳,但是沒有完成文件的改名和文件位置存儲,我使用Lua實現了。本來還使用了MySQL做了登錄驗證,但是使用lua寫的很尷尬,我寫到了FastDFS(第四種搭建文件系統的方式)。FastDFS也是用Nginx實現,嚴格來說是分佈式文件系統,CDN相關。

    提供了兩種文件上傳的方式,一種是上傳到大倉庫,一種是重命名到小文件夾。Nginx提供了文件上傳下載的功能,還是temp file,你需要使用Lua語言進行重新定義。FastDFS是將每個文件的相關信息,持久化到數據庫,方便查詢。

    安裝Nginx,安裝Lua環境,編譯啥的,服務器部署,自己去折騰吧,我都不好意思寫。。。。。。

四:上代碼

頁面代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>靜態資源服務器</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }

        /*1、清除浮動 雙僞元素清除浮動 */
        .clearfix:before, .clearfix:after {
            content: "";
            display: table; /* 這句話可以出發BFC BFC可以清除浮動,BFC我們後面講 */
        }

        .clearfix:after {
            clear: both;
        }

        .clearfix {
            *zoom: 1;
        }

        li {
            list-style: none;
        }
    </style>
</head>
<body>
<script src=""></script>


<form id="upload" method="POST" enctype="multipart/form-data"
      action="你自己的域名/upload"
      onsubmit="openProgressBar()">
    <p>File Upload</p>
    <input id="subpath" type="text" name="subpath" style="display: none">
    <input type="file" name="file" value="">
    <p>
        <input type="submit" name="upload" value="upload">
    </p>
</form>
<div>
    <div id="progress" style="width: 400px; border: 1px solid black">
        <div id="progressbar" style="width: 1px; background-color: blue; border: 1px solid white">&nbsp;</div>
    </div>
    <div id="tp">progress</div>
</div>


<script>
   // window.onload = function () { 畫蛇添足,頁面都加載完了,還刷新幹嘛
        interval = null;

        var req_url = window.location.search;

        function getPar(value) {
            var name = value.toLocaleString().split("=")
            document.getElementById("subpath").value = name[1]
        }

        getPar(req_url)

        function openProgressBar() {
            /* generate random progress-id */
            uuid = "";
            for (i = 0; i < 32; i++) {
                uuid += Math.floor(Math.random() * 16).toString(16);
            }
            /* patch the form-action tag to include the progress-id */
            document.getElementById("upload").action = "www.....域名/upload?X-Progress-ID=" + uuid;

            /* call the progress-updater every 1000ms */
            interval = window.setInterval(
                function () {
                    console.log(uuid)
                    fetch(uuid);
                },
                1000
            );
        }

        function fetch(uuid) {
            req = new XMLHttpRequest();
            req.open("GET", "域名/progress", 1);
            req.setRequestHeader("X-Progress-ID", uuid);
            req.onreadystatechange = function () {
                if (req.readyState == 4) {
                    if (req.status == 200) {
                        /* poor-man JSON parser */
                        var upload = eval(req.responseText);

                        document.getElementById('tp').innerHTML = upload.state;

                        /* change the width if the inner progress-bar */
                        if (upload.state == 'done' || upload.state == 'uploading') {
                            bar = document.getElementById('progressbar');
                            w = 400 * upload.received / upload.size;
                            bar.style.width = w + 'px';
                        }
                        /* we are done, stop the interval */
                        if (upload.state == 'done') {
                            window.clearTimeout(interval);
                        }
                    }
                }
            }
            req.send(null);
    }
</script>
</body>
</html>

Nginx  conf 配置代碼

### 文件服務器
location /mysql {
		default_type  text/plain;
		content_by_lua_file "/usr/local/openresty/nginx/conf/mylua/con_mysql.lua";
}
location /fileweb {      # 1.域名訪問
	  default_type  text/html;
	 alias /usr/local/dcWorkspace/staticWebInfo/staticIndex.html; # 2.靜態頁面,上傳文件
		upload_pass_args on;   #允許上傳參數到後臺
}
location /download {
		charset utf-8,gbk;
    alias /usr/local/dcWorkspace/publicDir/; #文件地址
    autoindex on;       
    autoindex_exact_size on; 
    autoindex_localtime on; 
}


location /upload {    #3.處理上傳的文件
		upload_cleanup 400 404 499 500-505;  #發生錯誤刪除文件
		upload_store_access user:rw;
		upload_limit_rate 10240k; #上傳速度限制
		client_max_body_size 2g; #上傳文件大小限制
		#limit_rate 100k; 
		#limit_conn addr 1;
		upload_pass_args on;   #允許上傳參數到後臺
		
		if (-d $cookie_username) {
		  set $user_name $cookie_username;
		}
		if (!-d $cookie_username){
		  set $user_name "nobody";
		}
		set $user_name "anybody";
		set $save_path "/usr/local/dcWorkspace/publicDir";  #文件保存路徑
		set $callback_path "/index" ;  #跳轉頁面
		upload_store $save_path;   
		
		upload_set_form_field "user_name" "KEYD";   
		upload_set_form_field "callback_path" $callback_path; 
		upload_set_form_field "save_path" $save_path;
    upload_set_form_field "sub_path" $http_referer;   
    upload_set_form_field "file_name" $upload_file_name;   
    upload_set_form_field "file_content_type" $upload_content_type;  
    upload_aggregate_form_field "file_md5" $upload_file_md5;  
    upload_aggregate_form_field "file_size" $upload_file_size;  
    upload_set_form_field "temp_path" $upload_tmp_path;  
    upload_pass_form_field "^.*$";   ## 提交所有表單字段
		upload_pass /processfile;  #4.上傳之後的操作  
		track_uploads dcproxied 5s;  #跟蹤進度信息,該信息在上傳完成後停留30s
}

location /processfile{  #5.處理文件
		lua_need_request_body on;  
        #6.對上傳的臨時文件進行保存,改名
		content_by_lua_file "/usr/local/openresty/nginx/conf/mylua/onupload.lua";  
}  

location /progress {  #獲取進度信息,6.前端上傳文件的進度條
    #report uploads tracked in the 'proxied' zone
    #upload_progress_json_output;
    report_uploads dcproxied;
		
}

 

        具體的文件處理部分:content_by_lua_file "/usr/local/openresty/nginx/conf/mylua/onupload.lua";  附件上傳

       做到這步驟,你的文件已經可以正常上傳,下載了,但是在臨時路徑,文件名是000000index這種格式,很怪。
        onupload.lua  資源://download.csdn.net/download/dadachenchen/12529326

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章