angular文件上传下载
时间: 2023-11-09 19:46:14 浏览: 50
在 Angular 中,可以使用 HttpClient 来进行文件上传和下载。
文件上传:
1. 首先,需要在 HTML 文件中添加一个 input 标签,用于选择文件:
```html
<input type="file" (change)="onFileSelected($event.target.files)">
```
2. 在组件中,需要定义一个方法来处理文件选择事件,并将选中的文件保存在一个变量中:
```typescript
selectedFile: File;
onFileSelected(files: FileList) {
this.selectedFile = files.item(0);
}
```
3. 接下来,需要编写一个方法来将文件上传到服务器:
```typescript
onUpload() {
const formData = new FormData();
formData.append('file', this.selectedFile);
this.http.post('http://example.com/upload', formData)
.subscribe(response => {
console.log('File uploaded successfully');
});
}
```
其中,`FormData` 是一个用于将表单数据转换为键值对的类,可以用来构建一个包含文件的表单数据。通过调用 `append` 方法,可以将文件添加到表单数据中。然后,使用 HttpClient 的 `post` 方法将表单数据发送到服务器。
文件下载:
1. 首先,需要定义一个方法来从服务器下载文件:
```typescript
onDownload() {
this.http.get('http://example.com/download', { responseType: 'blob' })
.subscribe(response => {
const blob = new Blob([response], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
window.open(url);
});
}
```
其中,`responseType: 'blob'` 表示响应数据的类型为 Blob 对象。然后,使用 Blob 构造函数将响应数据转换为 Blob 对象。接着,使用 `createObjectURL` 方法将 Blob 对象转换为 URL 地址,最后调用 `window.open` 方法打开下载链接即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)