gpt4 book ai didi

javascript - 在 ExpressJS 中向文件路径添加参数

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:22 24 4
gpt4 key购买 nike

我正在尝试上传引用我的 public/assets 目录中的客户文件夹的特定照片。文件路径应为 public/assets/:id。但是,从我的代码来看,当运行时,文件路径始终返回为 public/assets/undefined。有人对如何解决这个问题有建议吗?这是 express 中的代码。

app.param('id', function (req, res, next, id) {
console.log(req.params.id);
next();
});
app.post('/file-upload', function(req, res) {
// get the temporary location of the file
var tmp_path = req.files.thumbnail.path;
// set where the file should actually exists - in this case it is in the "images" directory
var target_path = './public/assets/'+req.params.id;
// move the file from the temporary location to the intended location
fs.rename(tmp_path, target_path, function(err) {
if (err) throw err;
// delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
fs.unlink(tmp_path, function() {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
});
});
});

最佳答案

在路由中,您没有传递参数,请检查并更改您的路由逻辑,如下所示

app.post('/file-upload/:id', function(req, res) {

var target_path = './public/assets/'+req.params.id; //or use req.param('id')

................

});

发布链接传递给你的第二个部分是你的 ID示例:http://localhost:port/file-upload/123

如果您遇到问题,请使用“使用‘?’将变量作为查询字符串传递”运算符

  app.post('/file-upload', function(req, res) {

var target_path = './public/assets/'+req.query.id;

................

});

像这样发布链接示例:http://localhost:port/file-upload?id=123

关于javascript - 在 ExpressJS 中向文件路径添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37928216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com