uni-app unicloud支付宝云前端页面托管能否提供全选删除功能 删除文件夹时需先删除内部文件
uni-app unicloud支付宝云前端页面托管能否提供全选删除功能 删除文件夹时需先删除内部文件
支付宝前端托管,暂时不支持删除非空文件夹。如果想递归删除所有文件。可以通过以下JS来实现 1、进入需要删除的目录(这一步很重要,用于确定要删除的根目录,别搞错了。否则 rm -rf / 就G了)
2、在network 中找到https://unicloud-api.dcloud.net.cn/unicloud/api/host/file-list这个接口,右击 copy - Copy as Fetch
2、创建一个js, 复制下方js
async function recursiveDelete(initialUrl, { headers: initialHeaders }) {
const urlParams = new URL(initialUrl).searchParams;
const commonParams = {
appid: urlParams.get(‘appid’) || “”,
provider: urlParams.get(‘provider’) || “”,
spaceId: urlParams.get(‘spaceId’) || “”
};
const rootFolder = urlParams.get(‘folder’);
async function makeRequest(url, options = {}) {
try {
const response = await fetch(url, {
headers: {
...initialHeaders,
'Content-Type': 'application/json;charset=UTF-8',
...options.headers
},
...options
});
return await response.json();
} catch (error) {
console.error(`请求错误:`, error.message);
return null;
}
}
function normalizePath(path) {
return path.startsWith('/') ? path.slice(1) : path;
}
async function deleteFile(file, folderPath) {
console.log('{ 【 folderPath 】 }:>>>>>>>>>>>> createFold.js:32', folderPath);
const normalizedPath = `${folderPath}${`/${folderPath}` === rootFolder ? '/' : ''}${file.name}`;
console.log(`尝试删除文件: ${normalizedPath}`);
const deleteResponse = await makeRequest('https://unicloud-api.dcloud.net.cn/unicloud/api/host/delete-file', {
method: 'POST',
body: JSON.stringify({ ...commonParams, fileId: file.id, filePath: normalizedPath })
});
if (deleteResponse?.ret === 0) {
console.log(`成功删除文件: ${normalizedPath}`);
return true;
}
console.error(`删除文件失败: ${normalizedPath},错误信息:${deleteResponse}`);
return false;
}
async function processFolder(folderUrl) {
console.log(`处理文件夹: ${folderUrl}`);
const listResponse = await makeRequest(folderUrl);
if (!listResponse || listResponse.ret !== 0) {
console.error(`无法列出文件夹内容: ${folderUrl}`);
return false;
}
const { directories, files } = listResponse.data;
const currentFolder = normalizePath(new URL(folderUrl).searchParams.get('folder'));
console.log(`文件夹 ${currentFolder} 包含 ${files.length} 个文件和 ${directories.length} 个子文件夹`);
await Promise.all(files.map(file => deleteFile(file, currentFolder)));
await Promise.all(directories.map(dir =>
processFolder(folderUrl.replace(/folder=[^&]+/, `folder=${encodeURIComponent(dir.prefix)}`))
));
await deleteFolderAttempt(currentFolder);
}
async function deleteFolderAttempt(folderPath) {
const normalizedPath = normalizePath(folderPath);
console.log(`尝试删除文件夹: ${normalizedPath}`);
const deleteResponse = await makeRequest('https://unicloud-api.dcloud.net.cn/unicloud/api/host/delete-directory', {
method: 'POST',
body: JSON.stringify({ ...commonParams, folder: normalizedPath })
});
if (deleteResponse && deleteResponse.ret === 0) {
console.log(`成功删除文件夹: ${normalizedPath}`);
} else {
console.log(`无法删除文件夹: ${normalizedPath},错误信息:${deleteResponse}`);
}
}
await processFolder(initialUrl);
console.log('递归删除过程完成');
}
3、将复制到的fetch方法粘贴到js中,并将fetch方法名修改为recursiveDelete
recursiveDelete(“https://unicloud-api.dcloud.net.cn/unicloud/api/host/file-list?appid=&provider=alipay&spaceId=”, {
“headers”: {
“accept”: “application/json, text/plain, /”,
“accept-language”: “zh-CN,zh;q=0.9”,
“cache-control”: “no-cache”,
“pragma”: “no-cache”,
“priority”: “u=1, i”,
“sec-ch-ua”: "“Chromium”;v=“130”, “Google Chrome”;v=“130”, “Not?A_Brand”;v=“99"”,
“sec-ch-ua-mobile”: “?0”,
“sec-ch-ua-platform”: ““macOS””,
“sec-fetch-dest”: “empty”,
“sec-fetch-mode”: “cors”,
“sec-fetch-site”: “same-site”,
“token”: “”
},
“referrer”: “https://unicloud.dcloud.net.cn/”,
“referrerPolicy”: “strict-origin-when-cross-origin”,
“body”: null,
“method”: “GET”,
“mode”: “cors”,
“credentials”: “include”
});
5、执行此方法 node recursiveDelete.js
备注:为了验证这个脚本的可用性。可以先创建一个文件夹来测试。这里附上一个shell用于创建复杂嵌套的目录结构供参考 #!/bin/bash
设置基本参数
BASE_DIR=“highly_complex_nested_structure”
MAX_DEPTH=7
MIN_DEPTH=2
MIN_FILES=1
MAX_FILES=5
MIN_FOLDERS=1
MAX_FOLDERS=5
MIN_SIBLING_FOLDERS=2
MAX_SIBLING_FOLDERS=5
创建基础目录
mkdir -p $BASE_DIR
cd $BASE_DIR
创建.gitignore文件
cat << EOF > .gitignore
*.log
*.tmp
.DS_Store
node_modules/
*.swp
EOF
generate_lorem_ipsum() {
local words=$1
curl -s “https://loripsum.net/api/1/short/plaintext” | tr -d ‘\n’ | cut -d’ ’ -f1-$words | sed ‘s/$/./’
}
create_random_file() {
local dir=$1
local file_type=$2
local filename
case $file_type in
"text")
filename=$(openssl rand -hex 8).txt
generate_lorem_ipsum 50 > "$dir/$filename"
;;
"markdown")
filename=$(openssl rand -hex 8).md
cat << EOF > "$dir/$filename"
$(generate_lorem_ipsum 3)
$(generate_lorem_ipsum 4)
$(generate_lorem_ipsum 20)
$(generate_lorem_ipsum 4)
- $(generate_lorem_ipsum 5)
- $(generate_lorem_ipsum 5)
- $(generate_lorem_ipsum 5)
$(generate_lorem_ipsum 3)
$(generate_lorem_ipsum 30)
EOF
;;
“json”)
filename=$(openssl rand -hex 8).json
cat << EOF > “$dir/$filename”
{
“id”: “$RANDOM”,
“name”: “$(generate_lorem_ipsum 2)”,
“description”: “$(generate_lorem_ipsum 10)”,
“details”: {
“category”: “$(generate_lorem_ipsum 1)”,
“tags”: [
“$(generate_lorem_ipsum 1)”,
“$(generate_lorem_ipsum 1)”,
“$(generate_lorem_ipsum 1)”
],
“created_at”: “$(date -u +”%Y-%m-%dT%H:%M:%SZ")"
},
“is_active”: $( (( RANDOM % 2 )) && echo “true” || echo “false” )
}
EOF
;;
“image”)
filename=$(openssl rand -hex 8).svg
local colors=(“red” “blue” “green” “yellow” “purple” “orange”)
local color=${colors[$RANDOM % ${#colors[@]}]}
local shape=$((RANDOM % 3))
case $shape in
0) # Circle
cat << EOF > “$dir/$filename”
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="$color" />
</svg>
EOF
;;
1) # Rectangle
cat << EOF > “$dir/$filename”
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<rect width="80" height="80" x="10" y="10" stroke="black" stroke-width="3" fill="$color" />
</svg>
EOF
;;
2) # Triangle
cat << EOF > “$dir/$filename”
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<polygon points="50,10 10,90 90,90" stroke="black" stroke-width="3" fill="$color" />
</svg>
EOF
;;
esac
;;
esac
echo "Created $file_type file: $dir/$filename"
}
create_files_in_folder() {
local current_path=$1
local num_files=$((RANDOM % (MAX_FILES - MIN_FILES + 1) + MIN_FILES))
for ((i=1; i<=num_files; i++)); do
local file_type=$((RANDOM % 4))
case $file_type in
0) create_random_file "$current_path" "text" ;;
1) create_random_file "$current_path" "markdown" ;;
2) create_random_file "$current_path" "json" ;;
3) create_random_file "$current_path" "image" ;;
esac
done
# 随机创建隐藏文件或文件夹
if [ $((RANDOM % 4)) -eq 0 ]; then
if [ $((RANDOM % 2)) -eq 0 ]; then
local hidden_file=".hidden_file_$RANDOM"
generate_lorem_ipsum 20 > "${current_path}/${hidden_file}"
echo "Created hidden file: ${current_path}/${hidden_file}"
else
local hidden_folder=".hidden_folder_$RANDOM"
mkdir -p "${current_path}/${hidden_folder}"
create_files_in_folder "${current_path}/${hidden_folder}"
echo "Created hidden folder: ${current_path}/${hidden_folder}"
fi
fi
}
create_nested_structure() {
local current_depth=$1
local current_path=$2
local max_depth=$((MIN_DEPTH + RANDOM % (MAX_DEPTH - MIN_DEPTH + 1)))
if [ $current_depth -gt $max_depth ]; then
return
fi
# 确保当前文件夹有内容
create_files_in_folder "$current_path"
# 创建子文件夹并递归
local num_folders=$((RANDOM % (MAX_FOLDERS - MIN_FOLDERS + 1) + MIN_FOLDERS))
for ((i=1; i<=num_folders; i++)); do
local sub_folder="folder_${current_depth}_${i}"
local new_path="${current_path}/${sub_folder}"
mkdir -p "$new_path"
echo "Created folder: $new_path"
create_nested_structure $((current_depth + 1)) "$new_path"
done
# 创建平级文件夹
local num_sibling_folders=$((RANDOM % (MAX_SIBLING_FOLDERS - MIN_SIBLING_FOLDERS + 1) + MIN_SIBLING_FOLDERS))
for ((i=1; i<=num_sibling_folders; i++)); do
local sibling_folder="sibling_${current_depth}_${i}"
local sibling_path="${current_path}/${sibling_folder}"
mkdir -p "$sibling_path"
echo "Created sibling folder: $sibling_path"
create_files_in_folder "$sibling_path"
done
}
create_complex_structure() {
local base_path=$1
local num_main_branches=$((RANDOM % (MAX_SIBLING_FOLDERS - MIN_SIBLING_FOLDERS + 1) + MIN_SIBLING_FOLDERS))
for ((i=1; i<=num_main_branches; i++)); do
local branch_name="main_branch_${i}"
local branch_path="${base_path}/${branch_name}"
mkdir -p "$branch_path"
echo "Created main branch: $branch_path"
create_nested_structure 1 "$branch_path"
done
}
开始创建目录
create_complex_structure “.”
内容这么多!点赞
回复 hws007: 老板不会运行node,你能发一下吗
帮忙看下为啥 assets 文件夹删不了啊,最底下我回复了
同问
暂不支持,支付宝那边正在开发相关功能
帮忙看下为啥 assets 文件夹删不了啊,最底下我回复了
我就这一个项目,突然自己多了很多根本删除不完,手动删除了就又生成了
阿里云云存储也无法删除文件夹
请求错误: fetch is not defined
回复 hws007: 老板,我不会运行node,你能发一下吗
为啥删到最后提示这个啊。。
当然可以。在使用uni-app和unicloud进行支付宝云前端页面托管时,你可以通过编写代码来实现全选删除功能,并在删除文件夹之前先删除其内部文件。以下是一个简单的示例代码,展示了如何实现这些功能。
1. 全选删除功能
假设你有一个文件列表,每个文件旁边都有一个复选框,用户可以选择多个文件进行删除。
前端代码(uni-app):
<template>
<view>
<checkbox-group @change="checkboxChange">
<block v-for="(file, index) in files" :key="index">
<checkbox :value="file.id">{{ file.name }}</checkbox>
</block>
</checkbox-group>
<button @click="deleteAll">删除选中</button>
</view>
</template>
<script>
export default {
data() {
return {
files: [
{ id: 1, name: 'file1.txt' },
{ id: 2, name: 'file2.txt' },
// 更多文件
],
selectedFiles: []
};
},
methods: {
checkboxChange(e) {
this.selectedFiles = e.detail.value;
},
deleteAll() {
const deletePromises = this.selectedFiles.map(fileId => {
return uniCloud.database().collection('files').doc(fileId).remove();
});
Promise.all(deletePromises).then(() => {
this.$api.toast('删除成功');
this.files = this.files.filter(file => !this.selectedFiles.includes(file.id));
this.selectedFiles = [];
}).catch(err => {
console.error('删除失败', err);
});
}
}
};
</script>
2. 删除文件夹前先删除内部文件
后端代码(uniCloud云函数):
// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init();
const db = cloud.database();
exports.main = async (event, context) => {
const folderId = event.folderId;
try {
// 获取文件夹内所有文件
const files = await db.collection('files').where({
folderId: folderId
}).get();
// 删除所有文件
const deletePromises = files.data.map(file => {
return db.collection('files').doc(file._id).remove();
});
await Promise.all(deletePromises);
// 删除文件夹
await db.collection('folders').doc(folderId).remove();
return {
success: true
};
} catch (err) {
console.error('删除失败', err);
return {
success: false,
error: err.message
};
}
};
上述代码展示了如何在uni-app中实现全选删除功能,并在uniCloud云函数中实现删除文件夹前先删除内部文件的逻辑。请根据实际需求调整数据库集合名称和字段名称。