我的 JavaScript 上传有问题: 我正在使用这个代码:
const handleParameterSearchUpload = async (event) => {
const files = event.target.files;
console.log(files);
const folders = {};
for (let i = 0; i < files.length; i++) {
const file = files[i];
const filePath = file.webkitRelativePath;
const pathParts = filePath.split('/');
// If the file is in a subfolder, add the file to the folder's list
if (pathParts.length > 2) {
const folderName = encodeURIComponent(pathParts[1]);
if (!folders[folderName]) {
folders[folderName] = [];
}
folders[folderName].push(file);
}
}
console.log(folders.length);
// Call processFiles for each folder
for (const folderName in folders) {
const folderFiles = folders[folderName];
await processFiles(folderFiles, true);
console.log("Processed", folderName);
}
parameterSearchInputRef.current.value = "";
};
处理文件夹中的文件。
这里使用此代码:
<input
type="file"
webkitdirectory="true"
style={{ display: 'none' }
ref={parameterSearchInputRef}
onChange={handleParameterSearchUpload}
/>
现在这个文件夹中有不为空的文件和子文件夹。 不幸的是我有一个问题。 当我上传文件夹时,文件会上传,但不会上传子文件夹。 代码不是问题,因为当我重命名文件夹时它工作正常,但是使用我上传的这个文件夹名称:
20240118-165159[param.defaults]CombinationParamSearch{sheets.l4_cortex_inh.params.cell.params.v_thresh_[-57.5, -58],sheets.l4_cortex_exc.AfferentConnection.base_weight_[0.0013, 0.0016, 0.0018]}
这不起作用。
不幸的是我总是将这些类型的文件夹上传到网页,如何解决这个问题? 子文件夹具有以下名称:
SelfSustainedPushPull_ParameterSearch_____base_weight_0.0013_v_thresh_-57.5
SelfSustainedPushPull_ParameterSearch_____base_weight_0.0013_v_thresh_-58
等等
不幸的是,基本问题是子文件夹似乎没有被上传,因为如果我登录控制台,子文件夹及其内部的内容都不会被记录。 我真的不知道如何在不使用像
fs
或 path
这样的包的情况下解决这个问题。有任何想法吗?不幸的是,我不能只要求用户重命名文件夹,因为这些文件夹名称是从另一个软件生成的。
据我所知,React 不喜欢
webkitdirectory
,而且 webkitdirectory
可能很快就会被弃用,转而使用 Dropzone。对此不太确定,但这是我在一些讨论中读到的内容。
对于包含目录和子目录的文件上传,将标准“HTML 文件 API”与
DirectoryReader
结合使用通常更有效。另一件需要考虑的事情是递归遍历目录结构。
以下是如何实现它的示例:
const handleParameterSearchUpload = async (event) => {
const traverseFiles = async (files) => {
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.isDirectory) {
const directoryReader = file.createReader();
const entries = await new Promise((resolve) => {
directoryReader.readEntries(resolve);
});
await traverseFiles(entries);
} else {
// Process the file
console.log("Uploading file:", file.name);
// Upload logic
}
};
const files = event.target.files;
console.log("Uploaded files:", files);
await traverseFiles(files);
// Clear `event.target.value` instead, since we can access the input element
// directly from the event object. No need for ref.
event.target.value = "";
};
为了以防万一,我还想提一下,编码后您需要使用
decodeURIComponent
来获取原始文件夹名称。