[6] Nginx Server Setup - Implementing Upload/Download + Simple Upload Client
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
With directory listing set up, let's implement file upload/download functionality using Drogon. --- ## 1. Server Function Implementation ### 1-1. Implementing Drogon Controller Register the Drogon Controller. (This step is required for it to be recognized during the build.) ``` cd /root/drogon2/drogon/build/drogon_ctl drogon_ctl create controller FileController ``` --- ### 1-2. Implement Upload/Download Functionality Source path: `/root/drogon2/drogon/build/drogon_ctl/testAPI/controllers` FileController.h #pragma once #include--- FileController.ccusing namespace drogon; class FileController : public HttpController { public: std::string _storagePath = "/root/storage/"; METHOD_LIST_BEGIN // Handles POST requests for "/upload" ADD_METHOD_TO(FileController::handleUpload, "/upload", Post); // Handles GET requests for "/download/{filename}" ADD_METHOD_TO(FileController::handleDownload, "/download/{1}", Get); METHOD_LIST_END // Method declarations void handleUpload(const HttpRequestPtr& req, std::function && callback); void handleDownload(const HttpRequestPtr& req, std::function && callback, const std::string& filename); }; #include "FileController.h" #includeAfter the above steps, navigate to the build directory and run `make`: ``` cd /root/drogon2/drogon/build/drogon_ctl/testAPI/build make ``` --- ### 1-3. Modify Drogon Configuration Edit `/root/drogon2/drogon/build/drogon_ctl/testAPI/config.json` and modify the `client_max_body_size` value (default is 1M). ``` "client_max_body_size": "256M" # Default is 1M, adjust as needed ``` If this value is not modified, a "413 Request Entity Too Large" error will be returned. With these modifications, the server setup is complete. --- ## 2. Client Function Implementation Add an HTML file at the following path: `/root/nginx/html/upload.html`#include // Upload handler void FileController::handleUpload(const HttpRequestPtr& req, std::function && callback) { Json::Value respStr; HttpStatusCode code = k200OK; MultiPartParser fileUpload; do { if (fileUpload.parse(req) != 0) { code = k400BadRequest; respStr = Json::Value("Multipart Format Invalid"); break; } auto &file = fileUpload.getFiles()[0]; LOG_INFO << "file:" << file.getFileName() << " (extension=" << file.getFileExtension() << ", type=" << file.getFileType() << ", len=" << file.fileLength() << ", md5=" << file.getMd5() << ")"; std::string uploadPath = _storagePath + file.getFileName(); LOG_INFO << "uploadPath:" << uploadPath.c_str(); if (file.saveAs(uploadPath) != 0) { code = k500InternalServerError; respStr = Json::Value("Internal Server Error"); break; } } while(false); auto resp = HttpResponse::newHttpResponse(); resp->setStatusCode(code); callback(resp); } // Download handler void FileController::handleDownload(const HttpRequestPtr& req, std::function && callback, const std::string& filename) { std::string filePath = _storagePath + filename; if (std::ifstream(filePath).good()) { auto resp = HttpResponse::newFileResponse(filePath.c_str(), filename.c_str()); resp->setContentTypeCode(CT_APPLICATION_OCTET_STREAM); resp->addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); callback(resp); } else { auto resp = HttpResponse::newHttpResponse(); resp->setStatusCode(k404NotFound); callback(resp); } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>File Upload</title> </head> <body> <h2>Upload a File</h2> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" required> <br><br> <button type="submit">Send</button> </form> </body> </html>--- ## 3. NGINX Configuration - Adjust the API alias settings - Also modify `client_max_body_size` ``` user nobody; worker_processes 10; events { worker_connections 1024; use epoll; } http { include mime.types; default_type application/octet-stream; sendfile on; client_max_body_size 256m; proxy_buffer_size 128k; proxy_buffers 4 256k; server { listen 10099; server_name localhost; location /doUpload { alias /root/nginx/html/; index upload.html; autoindex on; } location /list { alias /root/storage/; autoindex on; # Enable directory listing autoindex_exact_size off; # Display file size in simplified format (optional) autoindex_localtime on; # Display file time in local time (optional) } location /upload { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8848; # Proxy target server } location ~ ^/download/(.*) { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8848/download/$1; # Pass captured variable to backend } } } ``` If a "413 Request Entity Too Large" error occurs, adjust `client_max_body_size`. --- ## 4. Verifying Operation ### 4-1. Verify Upload Operation - Call the upload API and select a file using the client. --- - The server should respond with 200 OK. --- - Files are saved in the following path: ``` [root@vbox storage] $ ll Total 72 -rw-r--r--. 1 root root 66662 Nov 4 08:48 7.PNG -rw-r--r--. 1 nobody nobody 2 Nov 4 06:21 test.txt ``` You can also confirm this in the listing set up in “[5] NGINX Server Setup.” --- ### 4-2. Verify Download Operation - In a web browser, go to `http://127.0.0.1:10099/download/7.PNG` to confirm file download functionality. (While it is possible to download from the listing page, use the API directly to test the download function.) ``` # Download with wget; file size should match expected size [root@vbox ~] $ wget http://127.0.0.1:10099/download/7.PNG --2024-11-04 08:59:27-- http://127.0.0.1:10099/download/7.PNG Connecting to 127.0.0.1:10099... connected. HTTP request sent, awaiting response... 200 OK Length: 66662 (65K) [application/octet-stream] Saving to: `7.PNG' 7.PNG 100%[=====================================================================>] 65.10K --.-KB/s in 0s 2024-11-04 08:59:27 (397 MB/s) - `7.PNG' saved [66662/66662] ``` ------Related Links
---Recommended Link
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
이 블로그의 인기 게시물
한국 핵무장 논의와 방위산업 관련주: 핵무기 개발 과정과 유망 종목 분석
한국의 독자적 핵무장 논의가 주요 이슈로 떠오르며 방위산업 관련 주식들이 주목받고 있습니다. 특히, 핵무기 및 방어 관련 기술력을 보유한 기업들이 관심을 끌고 있어 투자자들에게 큰 잠재적 수혜가 예상됩니다. 트럼프 전 미국 대통령의 재집권 가능성 등 외교적 변화는 이러한 방위산업 관련주를 더욱 부각시키고 있습니다. ( 참조: https://gussconomy.tistory.com/entry/한국-핵무장-시나리오-관련주-투자-포인트-총정리 ) --- ### 핵무기 생산과정 요약 #### **핵연료 확보** : 고농축 우라늄-235 또는 플루토늄-239와 같은 핵분열 물질을 확보하는 과정입니다. - **우라늄 농축**: 우라늄-235의 비율을 약 90% 이상으로 높이는 과정입니다. - **플루토늄 생산**: 원자로에서 우라늄-238을 중성자로 포획하여 플루토늄을 생성하고 이를 화학적으로 분리합니다. #### **폭발 장치 개발** : 확보한 핵연료를 폭발할 수 있도록 설계된 장치입니다. - **충돌 방식 (Gun-type)**: 고농축 우라늄을 이용해 두 덩어리를 빠르게 결합시켜 핵분열을 유도합니다. - **내부 압축 방식 (Implosion-type)**: 고폭압력으로 플루토늄을 압축하여 임계 질량을 초과하도록 합니다. ####. **무기화 및 배치** - 폭발 장치를 무기 형태로 조립하여 배치 가능한 상태로 만드는 과정입니다. 미사일, 폭격기 등에 탑재될 수 있도록 설계합니다. --- ### 핵심적인 부분 가장 중요한 부분은 **핵연료 확보**와 **폭발 장치 개발**입니다. - **핵연료 확보**: 핵분열 물질 확보가 핵무기 개발의 필수 조건입니다. 우라늄 농축과 플루토늄 생산은 고도의 기술력을 요구하며, 보안과 국제적인 감시가 강화된 부분입니다. - **폭발 장치 개발**: 핵연료가 있어도 이를 효과적으로 폭발시키는 장치가 없다면 무기화가 불가능합니다. 압축 방식 등 폭발 장치 개발 기술이 핵무기의 폭발력...
[로스트아크] 제작 효율 최적화 위한 영지 세팅
### 1. 대성공 확률 증가 vs. 제작 수수료 절감 - **대성공 확률 증가**: 대성공 확률이 2% 증가해도 실제 효과는 크지 않습니다. 예를 들어, 기본 대성공 확률 5%에 2% 증가를 적용해도 실질적인 효과는 0.1% 증가에 불과합니다. - **제작 수수료 절감**: 제작 수수료를 2% 절감할 경우, 제작할 때마다 발생하는 골드 비용을 직접적으로 줄일 수 있어 비용 절약 효과가 훨씬 큽니다. - 결과적으로, 제작 수수료 절감이 대성공 확률 증가보다 약 10배 더 많은 이득을 제공합니다. 따라서 대성공 확률보다는 수수료 절감에 집중하는 것이 권장됩니다. --- ### 2. 효율적인 영지 세팅을 위한 이득 극대화 세팅 - 영지 내 필수 세팅 아이템으로 "곡예사의 대기실," "찬란한 소원 나무," "여신의 가호"가 추천됩니다. - **곡예사의 대기실**: 마리샵에서 블루 크리스탈로 구매할 수 있으며, 기본적인 제작 효율을 높이는 데 필수 아이템입니다. - **찬란한 소원 나무**: 수수료 절감을 제공하여 제작 비용을 절감하는 효과가 있어 이득 극대화에 도움이 됩니다. - **여신의 가호**: 미술품 42개를 모아 획득할 수 있으며, 추가적인 제작 효율을 제공합니다. 여유가 있다면 필수로 장착하는 것이 좋습니다. - 여신의 가호 대신, **곡예사의 무기 진열대**를 구매해 사용할 수도 있으며, 경제적인 선택지로 활용할 수 있습니다. --- ### 3. 의상 세팅 (선택적 적용) - 특정 의상을 착용하면 제작 효율이 약간 증가하지만, 최적의 의상 옵션은 없기 때문에 필수는 아닙니다. 크리스탈 비용이 부담스러울 경우 생략 가능하며, 다른 세팅을 우선적으로 강화하는 것이 좋습니다. - **드레스룸 이용**: 크리스탈을 사용하여 드레스룸에서 특정 NPC와의 호감도로 얻을 수 있는 의상을 구매할 수 있습니다. - **추천 의상**: 페...
[로스트아크] 로스트아크 생활 도구 옵션
### 생활 도구 옵션 및 확률 | **옵션** | **고급** | **희귀** | **영웅** | **전설** | **유물** | |-------------------------|-------------|------------|-------------|-------------|-------------| | 기본 보상 추가 획득률 | 5~10% | 10~20% | 15~30% | 20~40% | 25~50% | | 희귀 재료 획득률 | 5~10% | 10~20% | 15~30% | 20~40% | 25~50% | | 특수 획득 확률 | 0.5~1% | 1~2% | 1.5~3% | 2~4% | 2.5~5% | | 내구도 미차감 확률 | 2.5~5% | 5~10% | 7.5~15% | 10~20% | 12.5~25% | | 채집속도 | 1.25~2.5% | 2.5~5% | 3.75~7.5% | 5~10% | 6.25~12.5% | | 미니게임 난이도 하락 | 1 | 1~2 | 1~2 | 2~3 | 2~3 | | 미니게임 보상 획득 확률 | 5~10% | 10~20% | 15~30% | 20~40% | 25~50% | | 낚시 캐스팅 등급 | 1~2 | 2~4 | 4~6 | 6~8 | 8~10 | --- ### 생활 키트 옵션 정리 - 영웅 등급 생활 도구가 제작 비용면에서 효율 좋음 | **생활 유형** | **필수 옵션 (빨간색)...
댓글
댓글 쓰기