调用DeepSeek API 增强版纯前端实现方案,支持文件上传和内容解析功能 ...

打印 上一主题 下一主题

主题 1778|帖子 1778|积分 5334

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
以下是一个增强版纯前端实现方案,支持文件上传和内容解析功能,直接调用DeepSeek API:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>DeepSeek 智能助手 (支持附件)</title>
  6.     <style>
  7.         :root {
  8.             --primary-color: #2c3e50;
  9.             --accent-color: #3498db;
  10.             --error-color: #e74c3c;
  11.         }
  12.         body {
  13.             font-family: 'Segoe UI', system-ui, sans-serif;
  14.             max-width: 800px;
  15.             margin: 2rem auto;
  16.             padding: 0 20px;
  17.             background: #f8f9fa;
  18.         }
  19.         .container {
  20.             background: white;
  21.             border-radius: 12px;
  22.             box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  23.             padding: 2rem;
  24.         }
  25.         .input-group {
  26.             display: flex;
  27.             gap: 10px;
  28.             margin-bottom: 1rem;
  29.         }
  30.         input[type="text"], input[type="file"] {
  31.             flex: 1;
  32.             padding: 12px;
  33.             border: 2px solid #ddd;
  34.             border-radius: 8px;
  35.             font-size: 16px;
  36.         }
  37.         button {
  38.             padding: 12px 24px;
  39.             background: var(--accent-color);
  40.             color: white;
  41.             border: none;
  42.             border-radius: 8px;
  43.             cursor: pointer;
  44.             transition: opacity 0.3s;
  45.         }
  46.         button:hover {
  47.             opacity: 0.9;
  48.         }
  49.         #file-list {
  50.             margin: 1rem 0;
  51.             padding: 0;
  52.             list-style: none;
  53.         }
  54.         .file-item {
  55.             display: flex;
  56.             align-items: center;
  57.             padding: 8px;
  58.             background: #f8f9fa;
  59.             border-radius: 6px;
  60.             margin-bottom: 6px;
  61.         }
  62.         .file-item span {
  63.             flex: 1;
  64.             font-size: 0.9em;
  65.         }
  66.         #response {
  67.             margin-top: 20px;
  68.             padding: 16px;
  69.             background: #f8f9fa;
  70.             border-radius: 8px;
  71.             min-height: 100px;
  72.             white-space: pre-wrap;
  73.             line-height: 1.6;
  74.         }
  75.         .loading {
  76.             display: none;
  77.             color: #666;
  78.             font-style: italic;
  79.         }
  80.         .error {
  81.             color: var(--error-color);
  82.             margin: 0.5rem 0;
  83.         }
  84.     </style>
  85. </head>
  86. <body>
  87.     <div class="container">
  88.         <h1 style="color: var(--primary-color); margin-bottom: 1.5rem;">DeepSeek 智能助手</h1>
  89.         
  90.         <!-- 文件上传区域 -->
  91.         <div class="input-group">
  92.             <input type="file" id="file-input" multiple accept=".txt,.pdf,.docx">
  93.             <button onclick="handleFileUpload()">上传文件</button>
  94.         </div>
  95.         <ul id="file-list"></ul>
  96.         <!-- 问答区域 -->
  97.         <div class="input-group">
  98.             <input type="text" id="question" placeholder="请输入您的问题...">
  99.             <button onclick="askQuestion()">发送</button>
  100.         </div>
  101.         <div class="loading" id="loading">处理中...</div>
  102.         <div id="response"></div>
  103.     </div>
  104.     <script>
  105.         // 配置参数(⚠️ 安全提示:前端暴露API密钥仅限本地测试)
  106.         const CONFIG = {
  107.             API_KEY: 'your-api-key-here',
  108.             API_URL: 'https://api.deepseek.com/v1/chat/completions',
  109.             MODEL: 'deepseek-chat',
  110.             MAX_FILE_SIZE: 2 * 1024 * 1024, // 2MB
  111.             ALLOWED_TYPES: ['text/plain', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  112.         }
  113.         let uploadedFiles = [];
  114.         // 文件上传处理
  115.         async function handleFileUpload() {
  116.             const fileInput = document.getElementById('file-input');
  117.             const files = Array.from(fileInput.files);
  118.             const fileList = document.getElementById('file-list');
  119.             try {
  120.                 for (const file of files) {
  121.                     // 验证文件
  122.                     if (file.size > CONFIG.MAX_FILE_SIZE) {
  123.                         throw new Error(`文件 ${file.name} 超过大小限制 (最大 ${CONFIG.MAX_FILE_SIZE/1024/1024}MB)`);
  124.                     }
  125.                     if (!CONFIG.ALLOWED_TYPES.includes(file.type)) {
  126.                         throw new Error(`不支持的文件类型: ${file.type}`);
  127.                     }
  128.                     // 读取文件内容
  129.                     const content = await readFileContent(file);
  130.                     
  131.                     // 存储文件信息
  132.                     uploadedFiles.push({
  133.                         name: file.name,
  134.                         type: file.type,
  135.                         size: file.size,
  136.                         content: content,
  137.                         uploadedAt: new Date().toISOString()
  138.                     });
  139.                     // 更新文件列表
  140.                     const li = document.createElement('li');
  141.                     li.className = 'file-item';
  142.                     li.innerHTML = `
  143.                         <span>${file.name} (${formatFileSize(file.size)})</span>
  144.                         <button onclick="removeFile('${file.name}')">删除</button>
  145.                     `;
  146.                     fileList.appendChild(li);
  147.                 }
  148.                 fileInput.value = ''; // 清空选择
  149.             } catch (error) {
  150.                 showError(error.message);
  151.             }
  152.         }
  153.         // 文件内容读取
  154.         function readFileContent(file) {
  155.             return new Promise((resolve, reject) => {
  156.                 const reader = new FileReader();
  157.                 reader.onload = () => resolve(reader.result);
  158.                 reader.onerror = reject;
  159.                
  160.                 if (file.type === 'application/pdf') {
  161.                     // PDF处理需要第三方库(此处简化处理)
  162.                     reader.readAsArrayBuffer(file);
  163.                 } else {
  164.                     reader.readAsText(file, 'UTF-8');
  165.                 }
  166.             });
  167.         }
  168.         // 提问处理
  169.         async function askQuestion() {
  170.             const question = document.getElementById('question').value.trim();
  171.             const loading = document.getElementById('loading');
  172.             const responseDiv = document.getElementById('response');
  173.             if (!question) {
  174.                 showError('请输入有效问题');
  175.                 return;
  176.             }
  177.             try {
  178.                 loading.style.display = 'block';
  179.                 responseDiv.textContent = '';
  180.                 // 构建上下文
  181.                 const context = uploadedFiles.length > 0
  182.                     ? `参考文件内容:\n${uploadedFiles.map(f => f.content).join('\n')}\n\n问题:`
  183.                     : '';
  184.                 // API请求
  185.                 const response = await fetch(CONFIG.API_URL, {
  186.                     method: 'POST',
  187.                     headers: {
  188.                         'Content-Type': 'application/json',
  189.                         'Authorization': `Bearer ${CONFIG.API_KEY}`
  190.                     },
  191.                     body: JSON.stringify({
  192.                         model: CONFIG.MODEL,
  193.                         messages: [{
  194.                             role: "user",
  195.                             content: context + question
  196.                         }]
  197.                     })
  198.                 });
  199.                 if (!response.ok) throw new Error(`API请求失败: ${response.status}`);
  200.                 const data = await response.json();
  201.                 responseDiv.textContent = data.choices[0].message.content;
  202.             } catch (error) {
  203.                 showError(error.message);
  204.                 console.error(error);
  205.             } finally {
  206.                 loading.style.display = 'none';
  207.             }
  208.         }
  209.         // 辅助函数
  210.         function formatFileSize(bytes) {
  211.             if (bytes < 1024) return bytes + ' B';
  212.             if (bytes < 1048576) return (bytes/1024).toFixed(1) + ' KB';
  213.             return (bytes/1048576).toFixed(1) + ' MB';
  214.         }
  215.         function removeFile(filename) {
  216.             uploadedFiles = uploadedFiles.filter(f => f.name !== filename);
  217.             document.querySelectorAll('.file-item').forEach(li => {
  218.                 if (li.textContent.includes(filename)) li.remove();
  219.             });
  220.         }
  221.         function showError(message) {
  222.             const errorDiv = document.createElement('div');
  223.             errorDiv.className = 'error';
  224.             errorDiv.textContent = message;
  225.             document.body.appendChild(errorDiv);
  226.             setTimeout(() => errorDiv.remove(), 3000);
  227.         }
  228.         // 事件监听
  229.         document.getElementById('question').addEventListener('keypress', e => {
  230.             if (e.key === 'Enter') askQuestion();
  231.         });
  232.     </script>
  233. </body>
  234. </html>
复制代码
功能亮点

  • 文件上传管理

    • 支持多文件上传 (PDF/DOCX/TXT)
    • 实时表现文件列表
    • 文件巨细和类型验证
    • 单个文件删除功能

  • 内容处理

    • 主动将文件内容作为上下文附加到题目
    • 基础PDF/DOCX文件处理(需扩展解析逻辑)

  • 安全控制

    • 文件巨细限制 (2MB)
    • 允许的文件类型白名单

使用阐明

  • 生存为 .html 文件
  • 替换API密钥
  • 通过以下方式访问:
    1. # 使用Python启动简易服务器
    2. python3 -m http.server 8000
    复制代码
    访问 http://localhost:8000
扩展建议

  • 增强文件解析(需引入库):
  1. <!-- 在<head>添加 -->
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
  3. <script src="https://unpkg.com/mammoth@1.4.8/mammoth.browser.min.js"></script>
  4. <script>
  5. // 修改readFileContent函数
  6. async function readFileContent(file) {
  7.     if (file.type === 'application/pdf') {
  8.         const arrayBuffer = await file.arrayBuffer();
  9.         const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
  10.         let text = '';
  11.         for (let i = 1; i <= pdf.numPages; i++) {
  12.             const page = await pdf.getPage(i);
  13.             const content = await page.getTextContent();
  14.             text += content.items.map(item => item.str).join(' ');
  15.         }
  16.         return text;
  17.     } else if (file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
  18.         const arrayBuffer = await file.arrayBuffer();
  19.         const result = await mammoth.extractRawText({arrayBuffer});
  20.         return result.value;
  21.     }
  22.     return await file.text();
  23. }
  24. </script>
复制代码

  • 添加预览功能
  1. function previewFile(filename) {
  2.     const file = uploadedFiles.find(f => f.name === filename);
  3.     if (file) {
  4.         const win = window.open();
  5.         win.document.write(`<pre>${file.content}</pre>`);
  6.     }
  7. }
复制代码

  • 添加会话管理
  1. // 在CONFIG中添加
  2. SESSION_MAX_AGE: 3600 // 1小时有效期
  3. // 初始化时读取本地存储
  4. if (localStorage.getItem('chatSession')) {
  5.     const session = JSON.parse(localStorage.getItem('chatSession'));
  6.     if (Date.now() - session.timestamp < CONFIG.SESSION_MAX_AGE * 1000) {
  7.         uploadedFiles = session.files;
  8.         // 更新文件列表显示...
  9.     }
  10. }
  11. // 定期保存
  12. setInterval(() => {
  13.     localStorage.setItem('chatSession', JSON.stringify({
  14.         files: uploadedFiles,
  15.         timestamp: Date.now()
  16.     }));
  17. }, 30000);
复制代码
注意事项

  • 前端文件处理能力有限,大文件大概影响性能
  • 复杂文档解析建议在服务端进行
  • API密钥需通事后端服务保护(正式环境)
  • 欣赏器内存限制:建议添加文件数量限制
项目下载地址:
调用DeepSeek API 增强版纯前端实现方案,支持文件上传和内容解析功能

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

数据人与超自然意识

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表