vue 读取文件,编辑后另存为

<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="modifyFile">Modify File</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      file: null,
      fileContent: ''
    };
  },
  methods: {
    handleFileChange(e) {
      this.file = e.target.files[0];
    },
    modifyFile() {
      if (!this.file) {
        alert('Please select a file first.');
        return;
      }
 
      const reader = new FileReader();
      reader.onload = (e) => {
        this.fileContent = e.target.result;
        // Modify the file content here
        const modifiedContent = this.fileContent + '\nModified by Vue';
 
        // Create a new Blob with the modified content
        const blob = new Blob([modifiedContent], { type: this.file.type });
 
        // Create a URL for the new Blob
        const url = URL.createObjectURL(blob);
 
        // Create a download link for the new Blob and click it
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', this.file.name);
        document.body.appendChild(link);
        link.click();
 
        // Clean up the URL and the link
        URL.revokeObjectURL(url);
        document.body.removeChild(link);
      };
      reader.readAsText(this.file);
    }
  }
};
</script>

  

posted @ 2024-04-03 14:52  怪咖咖  阅读(67)  评论(0编辑  收藏  举报