我正在使用multer和fs上传图片文件 如何更改上传文件的目录,因为所有文件都存储在我的“routes”文件夹中,而不是由multer创建的“uploads” 另外,我如何更改名称文件示例:
username.jpg
这是我的代码:
var upload = multer({ dest: '/tmp' });
router.post('/file_upload', upload.single("file"), function (req, res) {
var file = __dirname + "/" + req.file.originalname;
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log(err);
} else {
res.redirect("back");
}
});
});
})
在客户端:
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload:
<br />
<form action="/file_upload" method="POST" enctype="multipart/form-
data">
<input type="file" name="file" />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
答案 0 :(得分:1)
除非您需要将上传的文件保留在原始上传位置,否则请执行以下操作:
var upload = multer({ dest: '/tmp' });
router.post('/file_upload', upload.single('file'), function (req, res) {
// Here change 'uploads' to the folder name you prefer.
// Also change req.file.originalname for your preferred file name
var file = path.join(__dirname, 'uploads', req.file.originalname)
fs.rename(req.file.path, file, function (err) {
if (err) {
console.log(err);
} else {
res.redirect("back")
}
})
})
答案 1 :(得分:1)
在存储变量
中声明您的目录var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './')//Declare it here where you want to store
},
filename: function (req, file, cb) {
cb(null, file.originalname);//You can give name here file.****
}
});
var upload = multer({
storage: storage
});
处理发布请求时
var path = req.files[0].path;
var imageName = req.files[0].originalname;//change name here
var imagepath = {};
imagepath['path'] = path;
imagepath['originalname'] = imageName; // name change
答案 2 :(得分:0)
您的变量文件不是指定您要写入文件的位置吗?
var file = __dirname + "/NewFolder/" + newFileName.jpg