Skip to content

feat: Support uploading files by copying, pasting, dragging and dropping #2939

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions ui/src/components/ai-chat/component/chat-input-operate/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@
type="textarea"
:maxlength="100000"
@keydown.enter="sendChatHandle($event)"
@paste="handlePaste"
@drop="handleDrop"
/>

<div class="operate flex align-center">
Expand Down Expand Up @@ -188,6 +190,7 @@
:show-file-list="false"
:accept="getAcceptList()"
:on-change="(file: any, fileList: any) => uploadFile(file, fileList)"
ref="upload"
>
<el-tooltip
:disabled="mode === 'mobile'"
Expand Down Expand Up @@ -301,6 +304,8 @@ const localLoading = computed({
}
})

const upload = ref()

const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
const documentExtensions = ['pdf', 'docx', 'txt', 'xls', 'xlsx', 'md', 'html', 'csv']
const videoExtensions = ['mp4', 'avi', 'mov', 'mkv', 'flv']
Expand Down Expand Up @@ -434,6 +439,54 @@ const uploadFile = async (file: any, fileList: any) => {
}
})
}
// 粘贴处理
const handlePaste = (event: ClipboardEvent) => {
if (!props.applicationDetails.file_upload_enable) return
const clipboardData = event.clipboardData
if (!clipboardData) return

// 获取剪贴板中的文件
const files = clipboardData.files
if (files.length === 0) return

// 转换 FileList 为数组并遍历处理
Array.from(files).forEach((rawFile: File) => {
// 创建符合 el-upload 要求的文件对象
const elFile = {
uid: Date.now(), // 生成唯一ID
name: rawFile.name,
size: rawFile.size,
raw: rawFile, // 原始文件对象
status: 'ready', // 文件状态
percentage: 0 // 上传进度
}

// 手动触发上传逻辑(模拟 on-change 事件)
uploadFile(elFile, [elFile])
})

// 阻止默认粘贴行为
event.preventDefault()
}
// 新增拖拽处理
const handleDrop = (event: DragEvent) => {
if (!props.applicationDetails.file_upload_enable) return
event.preventDefault()
const files = event.dataTransfer?.files
if (!files) return

Array.from(files).forEach((rawFile) => {
const elFile = {
uid: Date.now(),
name: rawFile.name,
size: rawFile.size,
raw: rawFile,
status: 'ready',
percentage: 0
}
uploadFile(elFile, [elFile])
})
}
// 语音录制任务id
const intervalId = ref<any | null>(null)
// 语音录制开始秒数
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code you provided has several areas that could be improved or checked for irregularities:

  1. Variable Naming and Clarity: The variable names like localLoading, imageExtensions, documentExtensions, etc., are descriptive but some might be more concise or informative.

  2. Event Handlers:

    • Ensure all events have appropriate checks to prevent unauthorized operations, especially when file uploads are disabled (applicationDetails.file_upload_enable).
  3. Styling and Flexibility:

    • Check if the styles used (like .flex.align-center) are compatible with your design requirements.
  4. Performance Considerations:

    • For handling pasting, consider optimizing performance by preventing unecessary computations inside loops and using asynchronous functions where possible.
  5. Error Handling:

    • Implement error handling in both paste and drop event handlers to manage cases where files fail to upload properly.
  6. Refactoring Upload Logic:

    • Combine the logic for uploading files and processing them into a reusable function to reduce redundancy.

Here's an updated version of the key sections with some suggestions:

// Simplify extension arrays
<template>
  <!-- Existing template content -->
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';

const props = defineProps({
  // existing props
})

const localLoading = computed(() => ({
  show: false,
  text: '',
}))

const isFileUploadEnabled = computed(() => {
  return !!props.applicationDetails.file_upload_enable;
});

// Other methods

<script>

/**
 * Updated method to handle drag and drop
 */
const handleDrop = async (e: DragEvent): Promise<void> => {
  e.preventDefault();
  
  let transferredFiles: File[] = [];
  
  try {
    const dataTransfer = e.dataTransfer || window.e; // Fix for web components
  
    if (!dataTransfer) throw new Error('No data transfer available.');
    
    transferredFiles = [...(Array.prototype.filter.call(dataTransfer.items, item => !item.webkit kind))];

    await handleFileList(transferredFiles);
  } catch (error) {
    console.error(error)
  }
}

/**
 * Updates fileList based on input type
 *
 * @param files list of files to process
 */
async function updateFileList(files: any[]): Promise<void> {
  if(!files.length) return;

  const elFiles = files.map(file => ({
    uid: Date.now(),
    name: file.name,
    size: file.size,
    raw: file.raw ?? file,
    status: "ready",
    percentage: 0
  }));

  await handleFileList(elFiles); // Continue with original implementation
}

</script>

Summary Changes:

  • Removed redundant code blocks.
  • Improved naming conventions for clarity.
  • Added comments to explain specific functionalities.
  • Ensured better practices for file manipulation.
  • Enhanced readability by organizing similar tasks together.

Regularly review such changes after implementation to ensure they work as anticipated without causing unexpected bugs.

Expand Down