feat: 新增选择文件上传功能,优化部分代码实现

This commit is contained in:
539943419 committed 2024-08-16 00:39:35 +08:00
1 parent 60477a9112
commit fda693326e
11 files changed
+292 -71

No files matched your search

+8 -5
View File
@@ -1,8 +1,11 @@
todo: 标签页,miaoDirectory切换动画 [finish] todo: 标签页,miaoDirectory切换动画 [finish]
todo: 重构virtualPage,所有page以插件形式使用 [finish] todo: 重构virtualPage,所有page以插件形式使用 [finish]
todo: miaoDirectory插件化,为后续插件功能开发做准备 [finish] todo: miaoDirectory插件化,为后续插件功能开发做准备 [finish]
todo: miaoPopupInput, 弹出一个输入框 todo: miaoPopupInput, 弹出一个输入框 [finish]
todo: miaoDirectory的重命名功能 [finish]
todo: miaoDirectory的剪切功能 [finish]
todo: miaoDirectory的上传按钮 [finish]
todo: VirtualDirectory更新时更新文件信息
todo: miaoDirectory的新建文件/文件夹功能 todo: miaoDirectory的新建文件/文件夹功能
todo: miaoDirectory的重命名功能 todo: miaoDirectory的复制文件/文件夹功能
todo: miaoDirectory的多选功能 todo: miaoDirectory的多选功能
todo: VirtualDirectory更新时更新文件信息
+12
View File
@@ -1,6 +1,9 @@
import generateId from "@/hooks/generateId"; import generateId from "@/hooks/generateId";
import useMiaoFetchApi from "@/hooks/useMiaoFetchApi";
import type { stats, file, directory } from "@/types/type.ts"; import type { stats, file, directory } from "@/types/type.ts";
const miaoFetchApi = useMiaoFetchApi();
export class VirtualFile { export class VirtualFile {
constructor(info: file, parent: VirtualDirectory) { constructor(info: file, parent: VirtualDirectory) {
this.name = info.name; this.name = info.name;
@@ -127,5 +130,14 @@ class VirtualDirectory {
return this.files?.includes(item) ?? false; return this.files?.includes(item) ?? false;
} }
} }
/**
* 调用后重新向远端拉取文件夹信息并进行更新
* @returns {void}
*/
async update(): Promise<void> {
const data: (file | directory)[] = await miaoFetchApi.get(this);
this.updateContent(data);
}
} }
export default VirtualDirectory; export default VirtualDirectory;
+5 -5
View File
@@ -35,12 +35,12 @@ const onClickoutside = async () => {
} }
const handleMainMouseLeave = async () => { const handleMainMouseLeave = async () => {
// setTimeout(() => { setTimeout(() => {
// showContextMenu.value -= 1
// }, 200)
nextTick(()=>{
showContextMenu.value -= 1 showContextMenu.value -= 1
}) }, 100)
// nextTick(()=>{
// showContextMenu.value -= 1
// })
} }
const handleSelect = async (key: string) => { const handleSelect = async (key: string) => {
@@ -40,6 +40,9 @@ import {
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import dateFormatter from '@/hooks/dateFormatter' import dateFormatter from '@/hooks/dateFormatter'
import useMiaoFetchApi from '@/hooks/useMiaoFetchApi'
const miaoFetchApi = useMiaoFetchApi()
const props = defineProps<{ const props = defineProps<{
item: VirtualDirectory | VirtualFile item: VirtualDirectory | VirtualFile
@@ -50,6 +53,7 @@ const props = defineProps<{
const emit = defineEmits<{ const emit = defineEmits<{
download: [] download: []
delete: [] delete: []
rename: []
dragStart: [event: DragEvent, item: VirtualDirectory | VirtualFile] dragStart: [event: DragEvent, item: VirtualDirectory | VirtualFile]
}>() }>()
@@ -66,10 +70,14 @@ const time = computed(() => {
const dropDownOptions = computed(() => { const dropDownOptions = computed(() => {
const options = [ const options = [
{
label: '重命名',
key: 'rename'
},
{ {
label: '删除', label: '删除',
key: 'delete' key: 'delete'
} },
] ]
if (itemType.value === 'file') { if (itemType.value === 'file') {
options.push( options.push(
@@ -84,8 +92,11 @@ const dropDownOptions = computed(() => {
return options return options
}) })
// 是不是可以直接在这里面实现?
const handleDropdownSelect = (key: string) => { const handleDropdownSelect = (key: string) => {
if (key === 'download') { if (key === 'rename') {
emit('rename')
} else if (key === 'download') {
emit('download') emit('download')
} else if (key === 'delete') { } else if (key === 'delete') {
emit('delete') emit('delete')
+2
View File
@@ -24,6 +24,7 @@ const _resolve = ref()
type popupConfigType = { type popupConfigType = {
title: string title: string
content?: string content?: string
inputValue?: string,
inputProps?: InputProps inputProps?: InputProps
options: { options: {
label: string label: string
@@ -36,6 +37,7 @@ const popupConfig = ref<popupConfigType>()
const popup = async (config: popupConfigType) => { const popup = async (config: popupConfigType) => {
popupConfig.value = config popupConfig.value = config
inputValue.value = config.inputValue ?? ''
showMask.value = true showMask.value = true
const key = await new Promise((resolve: (key: unknown) => unknown) => { const key = await new Promise((resolve: (key: unknown) => unknown) => {
_resolve.value = resolve _resolve.value = resolve
+3 -1
View File
@@ -7,7 +7,9 @@ export default {
get: '/get', get: '/get',
upload: '/upload', upload: '/upload',
delete: '/delete', delete: '/delete',
query: '/query' query: '/query',
rename: '/rename',
cut: '/cut'
}, },
enableUpload: true, enableUpload: true,
}; };
+47
View File
@@ -0,0 +1,47 @@
export const filePicker = (() => {
let _resolve: ((files: File[]) => void) | undefined;
return (option?: { accept?: "string"; multiple: boolean }) => {
if (_resolve) {
_resolve([]);
_resolve = undefined;
}
return new Promise<File[]>(resolve => {
const inpEle = document.createElement("input");
inpEle.id = `__file_${Math.ceil(Math.random() * 100000000)}`;
inpEle.type = "file";
inpEle.style.display = "none";
_resolve = resolve;
// 文件类型限制
// inpEle.accept="image/*"
option?.accept && (inpEle.accept = option?.accept);
// 多选限制
option?.multiple && (inpEle.multiple = option?.multiple);
// inpEle.addEventListener("change", event => fn.call(inpEle, event, inpEle.files), { once: true });
inpEle.addEventListener(
"change",
() => {
if (!inpEle.files) {
return;
}
const files: File[] = [];
let i = 0;
while (i < inpEle.files?.length) {
const _file = inpEle?.files?.item(i);
if (_file !== null) {
files.push(_file);
}
i += 1;
}
resolve(files);
_resolve = undefined
},
{ once: true }
);
inpEle.click();
});
};
})();
export default {
filePicker
};
+58 -10
View File
@@ -1,5 +1,5 @@
import VirtualDirectory, { VirtualFile } from "@/class/VirtualDirectory"; import VirtualDirectory, { VirtualFile } from "@/class/VirtualDirectory";
import { getOption, getResponse, miaoFetchConfig, deleteOption, uploadOption, queryOption } from "@/types/fetch"; import { getOption, getResponse, miaoFetchConfig, deleteOption, uploadOption, queryOption, renameOption, cutOption } from "@/types/fetch";
import Config from "@/config"; import Config from "@/config";
import axios, { AxiosRequestConfig } from "axios"; import axios, { AxiosRequestConfig } from "axios";
@@ -71,15 +71,15 @@ const miaoFetchApi = {
const formData = new FormData(); const formData = new FormData();
formData.append("file", data); formData.append("file", data);
// 必须这样传,不然中文乱码 // 必须这样传,不然中文乱码
formData.append("fileName", data.name) formData.append("fileName", data.name);
formData.append("oprateType", opType); formData.append("oprateType", opType);
return { return {
abort: () => abortMiaoFetch(), abort: () => abortMiaoFetch(),
response: new Promise<{ response: new Promise<{
message: 'success' | 'failed' message: "success" | "failed";
error?: string error?: string;
}>(async resolve => { }>(async resolve => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
@@ -107,7 +107,7 @@ const miaoFetchApi = {
return { return {
response: new Promise<{ response: new Promise<{
eventId: number eventId: number;
}>(async resolve => { }>(async resolve => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
@@ -117,6 +117,54 @@ const miaoFetchApi = {
}) })
}; };
}, },
/**
* 重命名对应的文件或文件夹
*/
rename(target: VirtualFile | VirtualDirectory, newName: string, option?: renameOption) {
const { baseUrl, api } = Config;
const url = `${baseUrl}${api.rename}${target.path}`;
const retry = option?.retry ?? 0;
const { miaoFetch } = useMiaoFetch({
retry
});
return {
response: new Promise<{
eventId: number;
}>(async resolve => {
const response = await miaoFetch({
url,
method: "post",
data: { newName }
});
resolve(response.data);
})
};
},
/**
* 剪切文件或文件夹
*/
cut(target: VirtualFile | VirtualDirectory, to: VirtualDirectory, option?: cutOption) {
const newPath = to.path
const { baseUrl, api } = Config;
const url = `${baseUrl}${api.cut}${target.path}`;
const retry = option?.retry ?? 0;
const { miaoFetch } = useMiaoFetch({
retry
});
return {
response: new Promise<{
eventId: number;
}>(async resolve => {
const response = await miaoFetch({
url,
method: "post",
data: { newPath }
});
resolve(response.data);
})
};
},
/** /**
* 查询服务端操作事件的进展 * 查询服务端操作事件的进展
@@ -130,15 +178,15 @@ const miaoFetchApi = {
}); });
return { return {
response: new Promise<{ response: new Promise<{
status: 'process' | 'success' | 'failed', status: "process" | "success" | "failed";
error?: unknown error?: unknown;
}>(async resolve => { }>(async resolve => {
const response = await miaoFetch({ const response = await miaoFetch({
url, url,
method: "get", method: "get",
params: { params: {
id: eventId id: eventId
} }
}); });
resolve(response.data); resolve(response.data);
}) })
+20 -21
View File
@@ -1,29 +1,28 @@
import { directory, file } from "./type"; import { directory, file } from "./type";
export type miaoFetchConfig = { export type miaoFetchConfig = {
retry?: number retry?: number;
} };
export type getOption = { export type getOption = {} & miaoFetchConfig;
} & miaoFetchConfig
export type getResponse = (file | directory)[] export type getResponse = (file | directory)[];
export type uploadOption = { export type uploadOption = {
/** /**
* 上传进度回调函数 * 上传进度回调函数
* @param {any} percent 进度百分比,float类型 * @param {any} percent 进度百分比,float类型
*/ */
onProcess?: (percent: number) => void onProcess?: (percent: number) => void;
/** /**
* 上传文件执行的操作 * 上传文件执行的操作
* write即为覆盖写 * write即为覆盖写
* append即为增量写 * append即为增量写
*/ */
type?: 'write' | 'append' type?: "write" | "append";
} & miaoFetchConfig } & miaoFetchConfig;
export type deleteOption = { export type deleteOption = {} & miaoFetchConfig;
} & miaoFetchConfig export type renameOption = {} & miaoFetchConfig;
export type queryOption = { export type cutOption = {} & miaoFetchConfig;
} & miaoFetchConfig export type queryOption = {} & miaoFetchConfig;
+114 -27
View File
@@ -1,5 +1,6 @@
<template> <template>
<miao-drop-handler @on-virtual-directory="handleDropVDirectory" @on-files="handleDropFiles"> <miao-drop-handler @on-virtual-directory="handleDropVDirectory" @on-files="handleDropFiles"
@on-virtual-files="handleDropVirtualFiles">
<div class="miao-directory-item-container" ref="rootDomRef"> <div class="miao-directory-item-container" ref="rootDomRef">
<div class="container-top" :style="{ <div class="container-top" :style="{
backgroundColor: backgroundColor:
@@ -43,23 +44,25 @@
<transition-group name="dirItem"> <transition-group name="dirItem">
<miaoDirectoryItem v-for="dir in showData_directory" @click="setCurrentDirectory(dir)" <miaoDirectoryItem v-for="dir in showData_directory" @click="setCurrentDirectory(dir)"
:item="dir" :key="dir.uid" :color="props.color" @delete="handleItemDelete(dir)" :item="dir" :key="dir.uid" :color="props.color" @delete="handleItemDelete(dir)"
@drag-start="handleItemDragStart" /> @drag-start="handleItemDragStart" @rename="handleItemRename(dir)" />
</transition-group> </transition-group>
<transition-group name="dirItem"> <transition-group name="dirItem">
<miaoDirectoryItem v-for="file in showData_files" :item="file" :key="file.uid" <miaoDirectoryItem v-for="file in showData_files" :item="file" :key="file.uid"
@click="openUrl(`${baseUrl}${api.get}${file.path}`)" @download=" @click="openUrl(`${baseUrl}${api.get}${file.path}`)" @download="handleItemDownload(file)"
openUrl(`${baseUrl}${api.get}${file.path}`, { @delete="handleItemDelete(file)" @drag-start="handleItemDragStart"
download: file.name @rename="handleItemRename(file)" :color="props.color" />
})
" @delete="handleItemDelete(file)" @drag-start="handleItemDragStart"
:color="props.color" />
</transition-group> </transition-group>
</n-scrollbar> </n-scrollbar>
</div> </div>
<div class="container-bottom" :style="{ <div class="container-bottom" :style="{
backgroundColor: backgroundColor:
index % 2 === 1 ? 'rgb(61 61 61)' : 'rgb(162 162 162)' index % 2 === 1 ? 'rgb(61 61 61)' : 'rgb(162 162 162)'
}"></div> }">
<div class="container-bottom-icon">
<cloud-upload-outline
:style="{ color: index % 2 === 0 ? 'rgb(0 0 0)' : 'rgb(255 255 255)' }" @click="handlePickFilesUpload"/>
</div>
</div>
<miao-mask v-model:show="showModel"></miao-mask> <miao-mask v-model:show="showModel"></miao-mask>
<miao-popup-input ref="popupInput"></miao-popup-input> <miao-popup-input ref="popupInput"></miao-popup-input>
</div> </div>
@@ -82,10 +85,12 @@ import {
CloudOutline, CloudOutline,
ChevronBackOutline, ChevronBackOutline,
ReloadOutline, ReloadOutline,
CloseOutline CloseOutline,
CloudUploadOutline
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import useUploadQueue from '@/hooks/useUploadQueue' import useUploadQueue from '@/hooks/useUploadQueue'
import useVirtualPages from '@/hooks/useVirtualPages' import useVirtualPages from '@/hooks/useVirtualPages'
import { filePicker } from '@/hooks/miaoTools'
const { baseUrl, api } = Config const { baseUrl, api } = Config
const dataBus = useDataBus() const dataBus = useDataBus()
@@ -195,6 +200,12 @@ const handleReload = () => {
reload() reload()
} }
const handleItemDownload = (item: VirtualFile) => {
openUrl(`${baseUrl}${api.get}${item.path}`, {
download: item.name
})
}
const handleItemDelete = async (item: VirtualDirectory | VirtualFile) => { const handleItemDelete = async (item: VirtualDirectory | VirtualFile) => {
const { response } = miaoFetchApi.delete(item, { const { response } = miaoFetchApi.delete(item, {
retry: 5 retry: 5
@@ -208,6 +219,39 @@ const handleItemDelete = async (item: VirtualDirectory | VirtualFile) => {
} }
} }
const handleItemRename = async (item: VirtualDirectory | VirtualFile) => {
const popupRes = await popupInput.value.popup({
title: '重命名',
showInput: true,
inputValue: item.name,
inputProps: {
placeholder: item.name,
},
options: [{
label: '取消',
key: false,
type: 'error'
}, {
label: '确认',
key: true,
type: 'success'
},]
})
if (popupRes.key === false) {
return
}
const newName = popupRes.text
const { response } = miaoFetchApi.rename(item, newName, {
retry: 5
})
const id = (await response).eventId
const { response: res } = miaoFetchApi.query(id)
const eventResult = await res
if (eventResult.status === 'success') {
reload()
}
}
const handleItemDragStart = async ( const handleItemDragStart = async (
_event: DragEvent, _event: DragEvent,
item: VirtualDirectory | VirtualFile item: VirtualDirectory | VirtualFile
@@ -232,26 +276,53 @@ const handleDropVDirectory = async (vDirs: VirtualDirectory[]) => {
if (vDirs[0].parent === currentDirectory.value) { if (vDirs[0].parent === currentDirectory.value) {
return return
} }
const popupRes = await popupInput.value.popup({ for (let dir of vDirs) {
title: '重命名', ; (async () => {
showInput: true, const _from = dir.parent
inputProps: { const { response } = miaoFetchApi.cut(dir, currentDirectory.value)
placeholder: '', const id = (await response).eventId
}, const { response: res } = miaoFetchApi.query(id)
options: [{ const eventResult = await res
label: '取消', if (eventResult.status === 'success') {
key: false, reload()
type: 'error' _from && _from.update()
}, { }
label: '确认', })()
key: true, }
type: 'success'
},]
})
console.log({ popupRes })
// setCurrentDirectory(vDirs[0]) // setCurrentDirectory(vDirs[0])
} }
const handleDropVirtualFiles = (files: VirtualFile[]) => {
if (files[0].parent === currentDirectory.value) {
return
}
for (let file of files) {
; (async () => {
const _from = file.parent
const { response } = miaoFetchApi.cut(file, currentDirectory.value)
const id = (await response).eventId
const { response: res } = miaoFetchApi.query(id)
const eventResult = await res
if (eventResult.status === 'success') {
reload()
_from.update()
}
})()
}
}
const handlePickFilesUpload = async () => {
const files = await filePicker({
multiple: true
})
const _currDir = currentDirectory.value
uploadQueue.push(files, _currDir, {
onFinish(){
_currDir.update()
}
})
}
onMounted(async () => { onMounted(async () => {
await setCurrentDirectory(currentDirectory.value) await setCurrentDirectory(currentDirectory.value)
}) })
@@ -372,6 +443,22 @@ $bottom-bar-height: 60px;
user-select: none; user-select: none;
box-shadow: 0px 1px 10px #888888; box-shadow: 0px 1px 10px #888888;
z-index: 2; z-index: 2;
.container-bottom-icon {
svg {
width: 30px;
height: 30px;
transition: all 0.3s ease;
cursor: pointer;
}
&:hover {
svg {
width: 40px;
height: 40px;
}
}
}
} }
} }
+10
View File
@@ -35,6 +35,16 @@ export default defineConfig({
changeOrigin: true, changeOrigin: true,
rewrite: path => path.replace(/^\/query/, "/query") rewrite: path => path.replace(/^\/query/, "/query")
}, },
"/rename": {
target: "http://127.0.0.1:17705",
changeOrigin: true,
rewrite: path => path.replace(/^\/rename/, "/rename")
},
"/cut": {
target: "http://127.0.0.1:17705",
changeOrigin: true,
rewrite: path => path.replace(/^\/cut/, "/cut")
},
} }
}, },
build: { build: {