概述
在centos7 使用nginx上传文件实现了nginx上传,但上传的文件名称都是一个10位的数字。这本非我所想要到结果,理想方案应该是根据上传的文件名称保存。
本想探索一下是否可以直接在nginx层面对文件重命名,方案倒是真的可以有,使用 Lua
之类的脚本语言来实现。鉴于功力不够,故暂不考虑。
故还是使用常规方案实现:新建一个node服务,使用nginx-upload-module
提供的upload_pass
参数将处理过的请求转发到我们的node服务上面。分两步走:
1. 修改nginx配置
修改nginx配置,将nginx-upload-module
存储文件的路径和文件名称塞到请求的body参数中。同时将请求转发到node服务:
具体配置:
location /upload {
upload_pass /res_upload;
upload_store /usr/local/nginx/html;
upload_resumable on;
upload_state_store /tmp/state;
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_aggregate_form_field "${upload_field_name}_md5" $upload_file_md5;
upload_aggregate_form_field "${upload_field_name}_size" $upload_file_size;
}
location /res_upload {
#default_type text/html;
#return 200 "success";
proxy_pass http://localhost:8080;
}
2. 新建node服务,重命名文件
-
查看请求中的form data:
-
解析请求中的form data为json形式:
根据文件位置,重命名文件
具体代码为:
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
let body = '';
req.on('data', chunk => {
body += chunk; // 获取form-data
});
req.on('end', () => {
console.log(body);
const params = parseForm(body); // json化参数
rename(params.file_path, params.file_name);
res.end('success: you can get it from: /' + params.file_name);
})
}).listen(8080)
function parseForm(data) {
const reg = /name="([\w_]+)"\s+(.+)\s/g;
const params = {};
let matched;
while((matched = reg.exec(data))){
params[matched[1]] = matched[2];
}
console.log(params);
return params;
}
function rename(source, name){
const path = require('path');
const dir = path.dirname(source);
fs.renameSync(source, path.join(dir, name));
}
福利
node服务在后台运行:
nohup node rename.js &
如果需要关闭这个服务:
ps ax | grep node
kill -9 pid