我正在使用FormData上传文件,并使用Multer在服务器端接收它。除了我在前端(https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry)上使用FileSystem API之外,其他所有操作均按预期进行,因此我上载的文件来自子目录。 Multer似乎只能看到文件名,即使我在将文件追加到表单数据(https://developer.mozilla.org/en-US/docs/Web/API/FormData/append)时明确为其设置了别名也是如此。看来Multer会在其余请求处理程序之前执行其逻辑,而看不到我在主体上设置的参数。我该如何思考完整的路径?
这是我当前设置的简化版本:
客户端(别名代表带路径的全名,file.name是FileSystem API自动设置的基本名称):
function upload(file, alias) {
let url = window.location.origin + '/upload';
let xhr = new XMLHttpRequest();
let formData = new FormData();
xhr.open('POST', url, true);
return new Promise(function (resolve, reject) {
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
resolve(file.name);
}
else if (xhr.readyState == 4 && xhr.status != 200) {
reject(file.name);
}
})
formData.append('file', file, alias || file.name); // this should in theory replace filename, but doesn't
formData.append('alias', alias || file.name); // an extra field that I can't see in multer function at all
xhr.send(formData);
});
}
服务器:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
// neither req nor file seems to contain any hint of the alias here
cb(null, file.originalname);
}
});
const upload = multer({storage: storage});
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/upload', upload.single('file'), function (req, res, next) {
// by this time the file seems to already be on disk with whatever name multer picked
if (req.file) {
res.status(200).end();
} else {
res.status(500).end();
}
});
最佳答案
为了使其正常工作,在配置preservePath
时使用multer
选项。以下将起作用:
const upload = multer({storage: storage, preservePath: true});
但是,需要注意的是,
multer
不会创建目录或子目录。这些必须事先创建。 (我也对此进行了测试。如果目录已创建且为空,则上传成功,但是,如果目录不存在,则上传失败)。他们在他们的readme中说:
“注意:当提供目标功能时,您负责创建目录。传递字符串时,multer将确保为您创建目录。”
该注释的后续内容将是:“您也负责创建任何子目录”。
上传的文件的相对路径可以在
originalname
属性中访问。因此,后端将如下所示:(如您所愿,但带有更新的注释)const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
// If you uploaded for example, the directory: myDir/myFile.txt,
// file.originalname *would* be set to that (myDir/myFile.txt)
// and myFile.txt would get saved to uploads/myDir
// *provided that* uploads/myDir already exists.
// (if it doesn't upload will fail)
// /* if( [ uploads/myDir doesn't exist ] ) { mkdir } */
cb(null, file.originalname);
}
});
实用提示:
在前端,我发现使用以下命令测试目录/子目录上传更加容易:(在Chrome上最新测试确定)
<form action="/uploads/multipleFiles" method="post" enctype="multipart/form-data">
<input type="file" name="multiple" webkitdirectory accept="text/*" onchange="console.log(this.files)" />
<input type="text" name="tester" value="uploadTester" />
<input type="submit"/>
</form>
关于javascript - 来自Multer中前端的自定义文件名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55977822/