最近nginx有需求实现上传feat,惊喜发现已经支持js了,因此尝试使用js实现上传。
nginx配置
为了支持njs需要模块加载
具体使用js业务模块,需要使用js相关指令
load_module指令需要放在全局即default.conf
下
例子如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| load_module modules/ngx_http_js_module.so;
events { }
http {
# 这里就不再限制了,nginx默认为1MB client_max_body_size 0;
js_path "/etc/nginx/njs/";
js_import main from upload.js;
server {
... location /upload-cert { js_content main.resolve; } ... }
|
njs模块业务代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const fs = require('fs'); const crypto = require('crypto'); const dest = `/var/www/ssl`;
function writeFile(fileContent, fileSuffix) { let fileName = `${crypto.createHash('md5').update(fileContent).digest("hex")}.${fileSuffix || 'crt'}`; fs.writeFileSync(`${dest}/${fileName}`, fileContent); return fileName; }
function upload(r) { let body = JSON.parse(r.requestBody); r.return(200, JSON.stringify({ crtFileName: writeFile(body.crtFile), keyFileName: writeFile(body.keyFile, 'key'), })); }
function main(r) { upload(r); }
export default {resolve: main}
|