angular上传图片_如何使用Angular轻松上传图片

angular上传图片

by Filip Jerga

由Filip Jerga

如何使用Angular轻松上传图片 (How to make image upload easy with Angular)

This is the second part of the tutorial on how to upload an image to Amazon S3. You can find the first part here. In this article, we will take a look at the Angular Part.

这是关于如何将图像上传到Amazon S3的教程的第二部分。 您可以在这里找到第一部分。 在本文中,我们将介绍角度部分。

You can also watch my step by step video tutorial of an image upload. The link is provided at the bottom of this article.

您也可以观看有关图像上传的分步视频教程。 该链接位于本文的底部。

1.首先创建一个模板 (1. Create a template first)

First, we want to create a reusable component that will be easily pluggable into other components.

首先,我们要创建一个可重用的组件,该组件可轻松插入其他组件。

Let’s start with a simple HTML template for our input. Don’t forget to apply styles of your choice, or you can get them from my GitHub repo.

让我们从一个简单HTML模板开始输入。 不要忘记应用您选择的样式,或者您可以从我的GitHub repo中获得它们。

<label class="image-upload-container btn btn-bwm">
  <span>Select Image</span>
  <input #imageInput
         type="file"
         accept="image/*"
         (change)="processFile(imageInput)">
</label>

Important here is a type of input, which is set to a file. The Accept attribute defines accepted files for input. Image/* specifies that we can choose images of any type by this input. #imageInput is a reference of input on which we can access uploaded files.

这里重要的是一种输入类型 ,它被设置为文件。 Accept属性定义接受的文件以供输入。 Image / *指定我们可以通过此输入选择任何类型的图像。 #imageInput是输入的参考,我们可以在该参考上访问上载的文件。

A Change event is fired when we select a file. So let’s take a look at the class code.

当我们选择一个文件时,将触发一个Change事件。 因此,让我们看一下类代码。

2.不要忘记组件代码 (2. Don’t forget for Component Code)

class ImageSnippet {
  constructor(public src: string, public file: File) {}
}

@Component({
  selector: 'bwm-image-upload',
  templateUrl: 'image-upload.component.html',
  styleUrls: ['image-upload.component.scss']
})
export class ImageUploadComponent {

  selectedFile: ImageSnippet;

  constructor(private imageService: ImageService){}

  processFile(imageInput: any) {
    const file: File = imageInput.files[0];
    const reader = new FileReader();

    reader.addEventListener('load', (event: any) => {

      this.selectedFile = new ImageSnippet(event.target.result, file);

      this.imageService.uploadImage(this.selectedFile.file).subscribe(
        (res) => {
        
        },
        (err) => {
        
        })
    });

    reader.readAsDataURL(file);
  }
}

Let’s break down this code. You can see in the processFile that we are getting an image input we sent from the change event. By writing imageInput.files[0] we are accessing the first file. We need a reader in order to access additional properties of a file. By calling readAsDataURL, we can get a base64 representation of an image in the callback function of the addEventListener we subscribed to before.

让我们分解一下这段代码。 您可以在processFile中看到 我们收到了来自change事件发送的图像输入。 通过写入imageInput.files [0],我们可以访问第一个文件 。 我们需要阅读器才能访问文件的其他属性。 通过调用readAsDataURL,我们可以在之前订阅的addEventListener的回调函数中获得图像的base64表示形式。

In a callback function, we are creating an instance of the ImageSnippet. The first value is a base64 representation of an image we will display later on the screen. The second value is a file itself, which we will send to the server for upload to Amazon S3.

在回调函数中,我们正在创建ImageSnippet的实例 第一个值是我们稍后将在屏幕上显示的图像的base64表示形式。 第二个值是文件本身,我们将其发送到服务器以上传到Amazon S3。

Now, we just need to provide this file and send a request through a service.

现在,我们只需要提供此文件并通过服务发送请求即可。

3.我们也需要服务 (3. We need a service as well)

It wouldn’t be an Angular app without a service. The service will be the one responsible for sending a request to our Node server.

没有服务就不会是Angular应用。 该服务将负责向我们的节点服务器发送请求。

export class ImageService {

  constructor(private http: Http) {}


  public uploadImage(image: File): Observable<Response> {
    const formData = new FormData();

    formData.append('image', image);

    return this.http.post('/api/v1/image-upload', formData);
  }
}

As I told you in the previous lecture, we need to send an image as part of the form data. We will append the image under the key of an image to form data (same key we configured before in Node). Finally, we just need to send a request to the server with formData in a payload.

正如我在上一讲中告诉您的那样,我们需要将图像作为表单数据的一部分发送。 我们将图像添加图像的项下,形成的数据(相同的密钥我们之前配置的节点)。 最后,我们只需要使用有效载荷中的formData向服务器发送请求。

Now we can celebrate. That’s it! Image sent to upload!

现在我们可以庆祝。 而已! 图片已上传!

In the next lines, I will provide some additional code for a better user experience.

在接下来的几行中,我将提供一些额外的代码以提供更好的用户体验。

4.其他UX更新 (4. Additional UX Updates)

class ImageSnippet {
  pending: boolean = false;
  status: string = 'init';

  constructor(public src: string, public file: File) {}
}

@Component({
  selector: 'bwm-image-upload',
  templateUrl: 'image-upload.component.html',
  styleUrls: ['image-upload.component.scss']
})
export class ImageUploadComponent {

  selectedFile: ImageSnippet;

  constructor(private imageService: ImageService){}

  private onSuccess() {
    this.selectedFile.pending = false;
    this.selectedFile.status = 'ok';
  }

  private onError() {
    this.selectedFile.pending = false;
    this.selectedFile.status = 'fail';
    this.selectedFile.src = '';
  }

  processFile(imageInput: any) {
    const file: File = imageInput.files[0];
    const reader = new FileReader();

    reader.addEventListener('load', (event: any) => {

      this.selectedFile = new ImageSnippet(event.target.result, file);

      this.selectedFile.pending = true;
      this.imageService.uploadImage(this.selectedFile.file).subscribe(
        (res) => {
          this.onSuccess();
        },
        (err) => {
          this.onError();
        })
    });

    reader.readAsDataURL(file);
  }
}

We added new properties to the ImageSnippet: Pending and Status. Pending can be false or true, depending if an image is currently being uploaded. Status is the result of the uploading process. It can be OK or FAILED.

我们向ImageSnippet添加了新属性:PendingStatus。 待定可以是false或true,具体取决于当前是否正在上传图像。 状态是上传过程的结果。 它可以是还是失败。

OnSuccess and onError are called after image upload and they set the status of an image.

上载图像后调用OnSuccessonError ,它们设置图像的状态。

Ok, now let’s take a look at the updated template file:

好的,现在让我们看一下更新的模板文件:

<label class="image-upload-container btn btn-bwm">
  <span>Select Image</span>
  <input #imageInput
         type="file"
         accept="image/*"
         (change)="processFile(imageInput)">
</label>


<div *ngIf="selectedFile" class="img-preview-container">

  <div class="img-preview{{selectedFile.status === 'fail' ? '-error' : ''}}"
       [ngStyle]="{'background-image': 'url('+ selectedFile.src + ')'}">
  </div>

  <div *ngIf="selectedFile.pending" class="img-loading-overlay">
    <div class="img-spinning-circle"></div>
  </div>

  <div *ngIf="selectedFile.status === 'ok'" class="alert alert-success"> Image Uploaded Succesfuly!</div>
  <div *ngIf="selectedFile.status === 'fail'" class="alert alert-danger"> Image Upload Failed!</div>
</div>

Here we are displaying our uploaded image and errors on the screen depending on the state of an image. When the image is pending, we also display a nice spinning image to notify the user of uploading activity.

在这里,我们根据图像状态在屏幕上显示上传的图像和错误。 当图像待处理时,我们还将显示一个漂亮的旋转图像,以通知用户上传活动。

5.添加一些样式 (5. Add some styling)

Stylings are not the focus of this tutorial, so you can get all of the SCSS styles in this link.

样式不是本教程的重点,因此您可以在此链接中获得所有SCSS样式。

Job done! :) That should be it for a simple image upload. If something is not clear, make sure you watched the first part of this tutorial first.

任务完成! :)就应该是一个简单的图像上传。 如果不清楚,请确保您首先观看了本教程的第一部分。

If you like this tutorial, feel free to check my full course on UdemyThe Complete Angular, React & Node Guide | Airbnb style app.

如果您喜欢本教程,请随时查看有关Udemy的完整课程- 《完整的Angular,React和Node指南》。 Airbnb风格的应用程序

Completed Project: My GitHub repository

完成的项目: 我的GitHub存储库

Video Lecture: YouTube Tutorial

视频讲座YouTube教程

Cheers,

干杯,

Filip

菲利普

翻译自: https://www.freecodecamp.org/news/how-to-make-image-upload-easy-with-angular-1ed14cb2773b/

angular上传图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值