Angular项目实现JSON文件上传下载重命名删除功能的方法咨询
Angular 实现JSON文件上传/下载/重命名/删除最简实现方案
以下实现全程使用Angular原生API和浏览器内置能力,无需引入第三方依赖,适合新手快速落地功能。
前置准备
首先确保你在对应功能模块(通常是AppModule)中导入了HttpClientModule,所有和后端交互的请求都依赖这个模块:
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; // 用到双向绑定时需要导入 import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule, FormsModule], bootstrap: [AppComponent] }) export class AppModule { }
1. JSON文件上传
支持前端直接解析JSON内容,也可以对接后端接口上传文件:
模板代码
<input type="file" accept=".json" (change)="onJsonUpload($event)" #fileInput hidden> <button (click)="fileInput.click()">选择JSON文件上传</button>
逻辑代码
// 组件内变量,存储上传解析后的JSON内容 uploadedJson: any = null; onJsonUpload(event: Event): void { const input = event.target as HTMLInputElement; if (!input.files?.length) return; const file = input.files[0]; // 校验文件格式 if (file.type !== 'application/json' && !file.name.endsWith('.json')) { alert('请上传JSON格式的文件'); return; } // 读取解析JSON内容 const reader = new FileReader(); reader.onload = (e) => { try { this.uploadedJson = JSON.parse(e.target?.result as string); console.log('JSON内容解析完成:', this.uploadedJson); // 如果需要上传到后端,打开下面的代码即可 // const formData = new FormData(); // formData.append('jsonFile', file); // this.http.post('你的后端上传接口', formData).subscribe({ // next: res => console.log('上传成功', res), // error: err => console.log('上传失败', err) // }) } catch (err) { alert('JSON文件内容格式错误,请检查后重新上传'); } }; reader.readAsText(file); }
2. JSON文件下载
直接通过浏览器原生API生成下载链接,无需后端支持:
模板代码
<button (click)="downloadJson()">下载JSON文件</button>
逻辑代码
// 要下载的JSON数据,可以是上传后修改的内容,也可以是后端返回的内容 downloadJsonData = { name: '测试数据', list: [1, 2, 3, 4] }; // 下载默认文件名,重命名功能会修改这个变量 downloadFileName = 'data.json'; downloadJson(): void { // 转成格式化的JSON字符串,方便阅读 const jsonStr = JSON.stringify(this.downloadJsonData, null, 2); // 生成Blob对象 const blob = new Blob([jsonStr], { type: 'application/json' }); // 生成临时下载链接 const tempUrl = window.URL.createObjectURL(blob); // 创建a标签触发下载 const a = document.createElement('a'); a.href = tempUrl; a.download = this.downloadFileName; a.click(); // 释放临时链接,避免内存泄漏 window.URL.revokeObjectURL(tempUrl); }
3. 文件重命名
核心逻辑是修改下载时的文件名参数,如果需要修改后端存储的文件名,对接后端接口即可:
模板代码
<div> <label>重命名文件:</label> <input type="text" [(ngModel)]="downloadFileName" placeholder="请输入文件名,自动补.json后缀"> </div>
后端重命名逻辑(可选)
renameRemoteFile(oldName: string, newName: string): void { // 自动补后缀 if (!newName.endsWith('.json')) newName += '.json'; this.http.put('你的后端重命名接口', { oldName, newName }).subscribe({ next: res => { this.downloadFileName = newName; console.log('重命名成功'); }, error: err => console.log('重命名失败', err) }) }
4. 文件删除
分前端本地删除和后端存储文件删除两种场景:
// 前端本地删除已上传的JSON deleteLocalJson(): void { this.uploadedJson = null; this.downloadFileName = 'data.json'; console.log('本地JSON已清空'); } // 后端存储文件删除 deleteRemoteFile(fileName: string): void { this.http.delete(`你的后端删除接口/${fileName}`).subscribe({ next: res => console.log('文件删除成功'), error: err => console.log('删除失败', err) }) }
新手注意事项
- 使用
[(ngModel)]双向绑定前,必须在对应模块中导入FormsModule - 所有
HttpClient请求建议都添加错误处理回调,避免未捕获的请求异常导致页面崩溃 - 可以自行添加文件名非法字符校验,避免下载或重命名时出现系统兼容问题
- 临时生成的
ObjectURL记得调用revokeObjectURL释放,防止内存泄漏
内容的提问来源于stack exchange,提问作者Mohamed Sameh Sellami
相关产品推荐
相关产品推荐

