網站首頁 編程語言 正文
一、安裝nginx容器
為了讓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
二、配置nginx
配置文件的路徑為/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
三、支持文件上傳
1. 配置nginx
上面的配置已經完成文件服務器的配置了,但是不能上傳文件,想要上傳文件,還需要做如下配置:
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
2. 添加upload.html
<!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>
3. 添加后面的處理服務
需要先安裝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)
四、獲取上傳進度
1.修改配置
# 開辟一個空間proxied來存儲跟蹤上傳的信息1MB upload_progress proxied 1m; server { …… location ^~ /progress { # 報告上傳的信息 report_uploads proxied; } location /upload { ... # 上傳完成后,仍然保存上傳信息5s track_uploads proxied 5s; } }
2. 修改上傳頁面
<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" style="width: 400px; border: 1px solid black"> <div id="progressbar" style="width: 1px; background-color: black; border: 1px solid white"> </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>
參考:
https://breeze2.github.io/blog/scheme-nginx-php-js-upload-process
https://www.tiantanhao.com/34031.html
https://blog.csdn.net/scugxl/article/details/107180138
https://octocat9lee.github.io/2020/03/11/Nginx%E6%90%AD%E5%BB%BA%E6%96%87%E4%BB%B6%E6%9C%8D%E5%8A%A1%E5%99%A8/
原文鏈接:https://blog.csdn.net/witton/article/details/124691338
相關推薦
- 2022-06-10 Docker部署springboot項目到騰訊云的實現步驟_docker
- 2023-01-19 詳解如何利用C#實現設置系統時間_C#教程
- 2022-05-14 .NetCore?Web?Api?利用ActionFilterAttribute統一接口返回值格式及
- 2022-09-09 React前端DOM常見Hook封裝示例下_React
- 2022-11-05 關于Linux下動態查看實時日志的命令_linux shell
- 2022-11-01 AndroidView與Compose框架交互實現介紹_Android
- 2022-09-13 Go語言對前端領域的入侵WebAssembly運行原理_Golang
- 2023-06-16 瞅一眼就能學會的GO并發編程使用教程_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支