我正试图从html表单中获取一个文件,并将其存储在另一个文件夹中。它基本上是云函数,我对node.js和firebase都是新手,所以不知道我做错了什么。我要做的是:
const fileMiddleware = require('express-multipart-file-parser');
app.post("/sendMail", (req, res) => {
const {
fieldname,
filename,
encoding,
mimetype,
buffer,
} = req.files[0];
console.log(req.files[0].originalname);
var fs = require('fs')
var oldPath = req.files[0].originalname;
var newPath = '/functions/'+oldPath;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
});
});
每当我试图移动文件时,我都会遇到路径问题。错误如下:
[Error: ENOENT: no such file or directory, rename 'C:UsersMaisum AbbasnowfunctionssendMail.txt'
> 'C:functionssendMail.txt'] {
> errno: -4058,
> code: 'ENOENT',
> syscall: 'rename',
> path: 'C:\Users\Maisum Abbas\now\functions\sendMail.txt',
> dest: 'C:\functions\sendMail.txt'
> }
此外,这是我想要实际移动文件的路径,但oldpath已经设置成这样了。
C:UsersMaisum AbbasnowfunctionssendMail.txt
由于我需要用电子邮件附加一个文件,这导致了路径问题。我用multer试过了,效果很好。我做了什么:
//call libraries here
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'resume/');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('filetoupload');
app.post("/careerMail", (req, res) => {
const { name } = req.body;
const { email } = req.body;
const { phone } = req.body;
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
});
const dest = 'mymail';
const mailOptions = {
from: email, // Something like: Jane Doe <janedoe@gmail.com>
to: dest,
subject: 'Candidate Application', // email subject
html: `<div>
<strong>From:</strong> ` +
name +
`<br /><br />
<strong>Email:</strong> ` +
email +
`<br /><br />
<strong>Phone:</strong> ` +
phone +
`<br /><br />
</div>
`,// email content in HTML
attachments: [
{
filename: req.files[0].originalname,
content: req.files[0].buffer.toString("base64"),
encoding: "base64"
}
]
and rest of the code...
我建议彻底重新思考这种方法。您将无法在已部署的函数中移动文件。nodejs运行时文件系统不允许在文件系统中的任何位置写入任何文件,除了os.tmpdir()
(在Linux上是/tmp(。
如果您需要临时写入一个文件,那么您绝对应该只使用tmp空间。请注意,写在那里的文件占用内存,应该在函数终止之前删除,否则可能会泄漏内存。
您可以读取与代码一起部署的文件,但应该通过相对路径进行读取。
我在移动文件时遇到了同样的问题。我使用一个函数来获取应用程序根文件夹,然后连接该位置的其余部分,从而对这个问题进行排序。
//place this file on application root.
//import where you need to get the root path.
const path = require('path');
module.exports = (function(){
return path.dirname(require.main.filename || process.mainModule.filename);
})();
//taking your case move location.
const rootPath = //require the above module.
const newPath = rootPath + /functions/' +oldPath;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
});