Vue加载项实现

在你的Vue加载项中,你需要实现一个按钮点击事件,将当前文档上传到Java后端接口。以下是实现代码:

登录后复制
<template>
  <div class="container">
    <button id="uploadFile" @click="uploadCurrentDocument">上传文档button>
  div>
template>

<script>
export default {
  methods: {
    async uploadCurrentDocument() {
      try {
        // 获取当前文档
        const app = window.WPSApplication;
        const doc = app.ActiveDocument;
        
        // 将文档保存为Blob对象
        const docBlob = await this.saveDocumentAsBlob(doc);
        
        // 创建FormData对象并添加文件
        const formData = new FormData();
        formData.append('file', docBlob, doc.Name);
        
        // 调用后端接口上传文件
        const response = await this.uploadToServer(formData);
        
        console.log('上传成功:', response);
        alert('文档上传成功!');
      } catch (error) {
        console.error('上传失败:', error);
        alert('文档上传失败: ' + error.message);
      }
    },
    
    async saveDocumentAsBlob(doc) {
      return new Promise((resolve, reject) => {
        // 临时保存文档到Blob
        doc.SaveAs2({
          FileName: doc.Name,
          FileFormat: wdFormatDocument, // 保存为原始格式
          AddToRecentFiles: false
        }, (result) => {
          if (result) {
            // 这里需要根据WPS API实际情况调整
            // 可能需要使用其他方法获取文件内容
            const fileContent = this.getFileContent(doc.Name);
            const blob = new Blob([fileContent], { type: 'application/octet-stream' });
            resolve(blob);
          } else {
            reject(new Error('保存文档失败'));
          }
        });
      });
    },
    
    // 模拟获取文件内容的方法
    getFileContent(fileName) {
      // 实际实现可能需要使用WPS API或其他方式获取文件内容
      // 这里只是示例
      return new Uint8Array(0);
    },
    
    async uploadToServer(formData) {
      const response = await fetch('http://your-java-backend-endpoint/upload', {
        method: 'POST',
        body: formData
        // 注意: 不需要设置Content-Type头部,浏览器会自动设置multipart/form-data
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      return await response.json();
    }
  }
}
script>

<style>
.container {
  padding: 10px;
}

#uploadFile {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#uploadFile:hover {
  background-color: #45a049;
}
style>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.

Java后端接口实现

以下是使用Spring Boot实现的Java后端接口,接收上传的文件并输出文件名:

登录后复制
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败,文件为空";
        }

        try {
            // 输出文件名
            String fileName = file.getOriginalFilename();
            System.out.println("接收到文件: " + fileName);
            
            // 这里可以添加文件处理逻辑,如保存到磁盘等
            // byte[] bytes = file.getBytes();
            // Path path = Paths.get("uploads/" + fileName);
            // Files.write(path, bytes);
            
            return "文件上传成功: " + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

注意事项

  1. 跨域问题:如果你的前端和后端不在同一个域名下,需要在Java后端配置CORS:
登录后复制
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*");
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  1. WPS API限制:WPS加载项中获取文档内容可能需要特定的API调用,上面的代码可能需要根据WPS实际API进行调整。
  2. 文件大小限制:在Spring Boot中,默认文件上传大小有限制,可以在application.properties中调整:
登录后复制
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
  • 1.
  • 2.