為了讓nginx支援檔案上傳,需要下載並執行帶有nginx-upload-module模組的容器:
sudo podman pull docker.io/dimka2014/nginx-upload-with-progress-modules:latest sudo podman -d --name nginx -p 83:80 docker.io/dimka2014/nginx-upload-with-progress-modules
該容器同時帶有nginx- upload-module模組和nginx-upload-progress-module模組。
注意該容器是Alpine Linux
,沒有bash,有些指令與其它發行版本的Linux不一樣。
使用下面的命令進入容器:
sudo podman exec -it nginx /bin/sh
作為檔案伺服器, 需要顯示本地時間,預設不是本地時間。透過下面一系列指令設定為本機時間:
apk update apk add tzdata echo "Asia/Shanghai" > /etc/timezone rm -rf /etc/localtime cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime apk del tzdata
建立檔案伺服器的根目錄:
mkdir -p /nginx/share
設定檔的路徑為/ etc/nginx/conf.d/default.conf
,作為
server { …… charset utf-8; # 设置字符编码,避免中文乱码 location / { root /nginx/share; # 根目录 autoindex on; # 开启索引功能 autoindex_exact_size off; # 关闭计算文件确切大小(单位bytes),只显示大概大小(单位kb、mb、gb) autoindex_localtime on; # 显示本地时间 } }
此時我們的檔案服務就配置好了,需要使用下面的指令讓設定生效:
nginx -s reload
上面的設定已經完成文件伺服器的設定了,但是不能上傳文件,想要上傳文件,還需要做如下配置:
server { …… charset utf-8; # 设置字符编码,避免中文乱码 client_max_body_size 32m; upload_limit_rate 1M; # 限制上传速度最大1M # 设置upload.html页面路由 location = /upload.html { root /nginx; # upload.html所在路径 } location /upload { # 限制上传文件最大30MB upload_max_file_size 30m; # 设置后端处理交由@rename处理。由于nginx-upload-module模块在存储时并不是按上传的文件名存储的,所以需要自行改名。 upload_pass @rename; # 指定上传文件存放目录,1表示按1位散列,将上传文件随机存到指定目录下的0、1、2、...、8、9目录中(这些目录要手动建立) upload_store /tmp/nginx 1; # 上传文件的访问权限,user:r表示用户只读,w表示可写 upload_store_access user:r; # 设置传给后端处理的表单数据,包括上传的原始文件名,上传的内容类型,临时存储的路径 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"; upload_pass_form_field "^submit$|^description$"; # 设置上传文件的md5值和文件大小 upload_aggregate_form_field "${upload_field_name}_md5" "$upload_file_md5"; upload_aggregate_form_field "${upload_field_name}_size" "$upload_file_size"; # 如果出现下列错误码则删除上传的文件 upload_cleanup 400 404 499 500-505; } location @rename { # 后端处理 proxy_pass http://localhost:81; } }
上面的配置中,暫時儲存時是按1位元散列來儲存的,需要在上傳目錄下手動建立0~9幾個目錄。
mkdir -p /tmp/nginx cd /tmp/nginx mkdir 1 2 3 4 5 6 7 8 9 0 chown nginx:root . -R
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>上传</title> </head> <body> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <form name="upload" method="POST" enctype="multipart/form-data" action="upload"> <input type="file" name="file"/> <input type="submit" name="submit" value="上传"/> </form> </body> </html>
需要先安裝python及所需的函式庫
apk add python3 pip3 install bottle pip3 install shutilwhich
python服務原始碼:
#!/usr/bin/python3 # -*- coding: utf-8 -*- from bottle import * import shutil @post("/upload") def postExample(): try: dt = request.forms.dict filenames = dt.get('file.name') tmp_path = dt.get("file.tmp_path") filepaths = dt.get("file.path") count = filenames.__len__() dir = os.path.abspath(filepaths[0]) for i in range(count): print("rename %s to %s" % (tmp_path[i], os.path.join(dir, filenames[i]))) target = os.path.join(dir, filenames[i]) shutil.move(tmp_path[i], target) shutil.chown(target, "nginx", "root") # 由于shutil.move不会保持用户归属,所以需要显示修改,否则访问时会报403无访问权限 except Exception as e: print("Exception:%s" % e) redirect("50x.html") # 如果是在容器中部署的nginx且映射了不同的端口,需要指定IP,端口 redirect('/') # 如果是在容器中部署的nginx且映射了不同的端口,需要指定IP,端口 run(host='localhost', port=81)
# 开辟一个空间proxied来存储跟踪上传的信息1MB upload_progress proxied 1m; server { …… location ^~ /progress { # 报告上传的信息 report_uploads proxied; } location /upload { ... # 上传完成后,仍然保存上传信息5s track_uploads proxied 5s; } }
<form id="upload" enctype="multipart/form-data" action="/upload" method="post" onsubmit="openProgressBar(); return true;"> <input name="file" type="file" label="fileupload" /> <input type="submit" value="Upload File" /> </form> <div> <div id="progress" > <div id="progressbar" > </div> </div> <div id="tp">(progress)</div> </div> <script type="text/javascript"> var interval = null; var uuid = ""; function openProgressBar() { for (var i = 0; i < 32; i++) { uuid += Math.floor(Math.random() * 16).toString(16); } document.getElementById("upload").action = "/upload?X-Progress-ID=" + uuid; /* 每隔一秒查询一下上传进度 */ interval = window.setInterval(function () { fetch(uuid); }, 1000); } function fetch(uuid) { var 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) { var upload = eval(req.responseText); document.getElementById('tp').innerHTML = upload.state; /* 更新进度条 */ if (upload.state == 'done' || upload.state == 'uploading') { var bar = document.getElementById('progressbar'); var w = 400 * upload.received / upload.size; bar.style.width = w + 'px'; } /* 上传完成,不再查询进度 */ if (upload.state == 'done') { window.clearTimeout(interval); } if (upload.state == 'error') { window.clearTimeout(interval); alert('something wrong'); } } } } req.send(null); } </script>#
以上是在容器中怎麼使用nginx來搭建上傳下載的檔案伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!