博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angular上传图片_如何使用Angular轻松上传图片
阅读量:2518 次
发布时间:2019-05-11

本文共 6844 字,大约阅读时间需要 22 分钟。

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 . 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 .

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

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
{ 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:

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

Image Uploaded Succesfuly!
Image Upload Failed!

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 .

样式不是本教程的重点,因此您可以在此获得所有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 Udemy — .

如果您喜欢本教程,请随时查看有关Udemy的完整课程-

Completed Project:

完成的项目:

Video Lecture:

视频讲座

Cheers,

干杯,

Filip

菲利普

翻译自:

angular上传图片

转载地址:http://sugwd.baihongyu.com/

你可能感兴趣的文章
爱的十个秘密--9.承诺的力量
查看>>
【吵架不能吵半截】
查看>>
电子书下载:Silverlight 4: Problem – Design – Solution
查看>>
为Vmware硬盘减肥瘦身
查看>>
YTT的提问以及由此引出的未来规划之思考
查看>>
QTP8.2--安装流程
查看>>
一步一步点亮Led
查看>>
POJ 3630 Phone List [Trie]
查看>>
springmvc 可以设置 <welcome-file>test.do</welcome-file>
查看>>
多Form界面控件状态变化问题分析
查看>>
面试记-(1)
查看>>
压力测试 相关
查看>>
MyBatis 通过 BATCH 批量提交
查看>>
android update automatically ( android 自动升级)
查看>>
session cookie
查看>>
POJ 1222 EXTENDED LIGHTS OUT(翻转+二维开关问题)
查看>>
【BZOJ-4059】Non-boring sequences 线段树 + 扫描线 (正解暴力)
查看>>
几种简单的负载均衡算法及其Java代码实现
查看>>
TMS3705A PCF7991AT 线路图
查看>>
安装Hadoop
查看>>