角度文件上传 [英] Angular File Upload

查看:65
本文介绍了角度文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的初学者,我想知道如何创建Angular 5 文件上传部分,我正在尝试查找任何教程或文档,但在任何地方都看不到任何内容.有什么想法吗?我尝试了 ng4-files ,但是它不适用于Angular 5

I'm a beginner with Angular, I want to know how to create Angular 5 File upload part, I'm trying to find any tutorial or doc, but I don't see anything anywhere. Any idea for this? And I tried ng4-files but it's not working for Angular 5

推荐答案

以下是将文件上传到api的有效示例:

Here is a working example for file upload to api:

步骤1:HTML模板(file-upload.component.html)

定义类型为file的简单输入标签.在(change) -event中添加一个用于处理选择文件的功能.

Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

第2步:使用TypeScript(file-upload.component.ts)上传处理

为所选文件定义默认变量.

Define a default variable for selected file.

fileToUpload: File = null;

创建在文件输入标签的(change)事件中使用的功能:

Create function which you use in (change)-event of your file input tag:

handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
}

如果要处理多文件选择,则可以遍历此文件数组.

If you want to handle multifile selection, than you can iterate through this files array.

现在通过调用file-upload.service创建文件上传功能:

Now create file upload function by calling you file-upload.service:

uploadFileToActivity() {
    this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
        console.log(error);
      });
  }

第3步:文件上传服务(file-upload.service.ts)

通过POST方法上传文件时,您应该使用FormData,因为这样您可以将文件添加到http请求中.

By uploading a file via POST-method you should use FormData, because so you can add file to http request.

postFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'your-destination-url';
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

所以,这是一个非常简单的工作示例,我每天在工作中都会使用它.

So, This is very simple working example, which I use everyday in my work.

这篇关于角度文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆