Nginx+Lua 搭建文件服务器

本文详细介绍使用Nginx和Lua搭建文件服务器的过程,包括文件上传、改名、存储及进度跟踪功能。涵盖Nginx配置、Lua脚本编写及前端进度条实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面详细的介绍前面第三种方式的搭建:


一:先上图,

前端界面

二:跳转页面

三:功能介绍

    网上有很多使用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.youkuaiyun.com/download/dadachenchen/12529326

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值