Node.js と Multer を使用して、いくつかの画像ファイルを「アップロード」フォルダーにアップロードしています。その部分はうまく機能しているようです。適切なファイル拡張子 (.jpg、.png、.gif など) がファイル名に追加されるように、アップロード後にファイルの名前を変更したいと考えています。
これを達成するために「fs.rename」を使用しようとしていますが、失敗します。エラーは発生しません...コンソール ログを調べると、名前を変更する「元の」パスと「ターゲット」パスは正しいようです。私のコードは以下のとおりです...誰かこれについて説明がありますか? これは非常に紛らわしいです、事前に感謝します。
//A means of ensuring only images are uploaded.
//note 'files' is an array of image files, omitted for clarity
var len = files.length;
var i;
for (i = 0; i < len; i++) {
if (files[i] != "undefined") {
const host = req.hostname;
const filePath = req.protocol + "://" + host + '/' + files[i].path;
const image = files[i].mimetype.startsWith('image/');
const type = files[i].mimetype.toString();
if(image) {
console.log('photo #' + i + ' uploaded');
console.log('uploaded file: ' + files[i].filename + ' saved within: ' + files[i].destination + ' at path: ' + files[i].path);
console.log('photo #' + i + ' filepath: ' + filePath);
console.log('photo #' + i + ' image extension is: ' + type);
console.log('photo #' + i + ' TYPEOF is: ' + typeof type);
var cutoff = type.split("/"); //"split" on "backslash"
var oldPath = req.protocol + "://" + host + ':8080' + '/uploads/' + files[i].filename
var targetPath = req.protocol + "://" + host + ':8080' + '/uploads' + '/image' + i + "." + cutoff[1]
console.log('photo #' + i + ' cutoff: ' + cutoff[1]);
console.log('ORIGINAL path for photo #' + i + ' is: ' + oldPath);
console.log('RENAMED target path for photo #' + i + ' is: ' + targetPath);
fs.rename(oldPath, targetPath, function(err) {
if (err) {
console.log("Unable to rename photo #" + i + " file...!")
} else {
console.log("Successfully renamed the file!")
}
})
// ...save filePath to database...if desired...
} else {
console.log("file # " + i + " received--however wrong format");
}
} //if NOT 'undefined'
} //for loop
コンソール ログを表示する実行の出力を次に示します。
photo #0 uploaded
uploaded file: identification-1572752074000 saved within: ./uploads at path: uploads\identification-1572752074000
photo #0 filepath: http://localhost/uploads\identification-1572752074000
photo #0 image extension is: image/jpeg
photo #0 TYPEOF is: string
photo #0 cutoff: jpeg
ORIGINAL path for photo #0 is: http://localhost:8080/uploads/identification-1572752074000
RENAMED target path for photo #0 is: http://localhost:8080/uploads/image0.jpeg
photo #1 uploaded
uploaded file: identification-1572752074015 saved within: ./uploads at path: uploads\identification-1572752074015
photo #1 filepath: http://localhost/uploads\identification-1572752074015
photo #1 image extension is: image/jpeg
photo #1 TYPEOF is: string
photo #1 cutoff: jpeg
ORIGINAL path for photo #1 is: http://localhost:8080/uploads/identification-1572752074015
RENAMED target path for photo #1 is: http://localhost:8080/uploads/image1.jpeg
Unable to rename photo #2 file...!
Unable to rename photo #2 file...!
もう1つの奇妙なことは、ループが「写真#2」に進むことです...「ファイル」配列には2つの画像しかないため(「0」と「1」)、そうではないはずです...それがそうであるかどうかはわかりませんここで私の問題に関連しています。提案をありがとう。