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 #imageInputtype="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 #imageInputtype="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 Udemy — The 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上傳圖片

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393411.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393411.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393411.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java小知識-----Map 按Key排序和按Value排序

Map排序的方式有很多種&#xff0c;這里記錄下自己總結的兩種比較常用的方式&#xff1a;按鍵排序(sort by key)&#xff0c; 按值排序(sort by value)。 1、按鍵排序 jdk內置的java.util包下的TreeMap<K,V>既可滿足此類需求&#xff0c;向其構造方法 TreeMap(Comparator…

社區帖子全文搜索實戰(基于ElasticSearch)

要為社區APP的帖子提供全文搜索的功能&#xff0c;考察使用ElasticSearch實現此功能。 ES的安裝不再描述。 es集成中文分詞器(根據es版本選擇對應的插件版本)下載源碼&#xff1a;https://github.com/medcl/elasticsearch-analysis-ik  maven編譯得到&#xff1a;elasticsear…

Microsoft Deployment Toolkit 2010 新功能實戰之一

續Microsoft Deployment Toolkit 2010 Beta 2先睹為快&#xff01;下面將通過使用Microsoft Deployment Toolkit 2010來部署Windows 7來介紹它的新功能的具體操作。有些概念的理解和操作方法參見MDT2008部署之一概覽。 一、實驗環境操作全部在VMware Workstation的虛擬操作環境…

leetcode1482. 制作 m 束花所需的最少天數(二分法)

給你一個整數數組 bloomDay&#xff0c;以及兩個整數 m 和 k 。 現需要制作 m 束花。制作花束時&#xff0c;需要使用花園中 相鄰的 k 朵花 。 花園中有 n 朵花&#xff0c;第 i 朵花會在 bloomDay[i] 時盛開&#xff0c;恰好 可以用于 一束 花中。 請你返回從花園中摘 m 束…

sublime 消除鋸齒_如何在Sublime中消除麻煩

sublime 消除鋸齒by Abdul Kadir通過阿卜杜勒卡迪爾(Abdul Kadir) 如何在Sublime中消除麻煩 (How to lint away your troubles in Sublime) Sublime is a lightweight text editor and is quite popular among many web developers. Now I know there are many sophisticated …

node.js mysql防注入_避免Node.js中的命令行注入安全漏洞

在這篇文章中&#xff0c;我們將學習正確使用Node.js調用系統命令的方法&#xff0c;以避免常見的命令行注入漏洞。我們經常使用的調用命令的方法是最簡單的child_process.exec。它有很一個簡單的使用模式;通過傳入一段字符串命令&#xff0c;并把一個錯誤或命令處理結果回傳至…

Netbackup detected IBM drives as unusable

今天在遠程給客戶安裝NBU的時候&#xff0c;遇到了下面這個問題&#xff0c;下面的內容來至于SYMANTEC。 1&#xff0c;更新mapping文件 在原來也遇到過類型的故障&#xff0c;通過更新mapping文件后&#xff0c;故障解決&#xff0c;這次沒有那么幸運了。 2&#xff0c;lsscsi…

opencv python運動人體檢測

采用非極大值抑制&#xff0c;將重疊的框合并成一個。 # import the necessary packages from imutils.object_detection import non_max_suppression import numpy as np import imutils import cv2# initialize the HOG descriptor/person detector hog cv2.HOGDescriptor()…

php mysql 注入一句話木馬_滲透技術--SQL注入寫一句話木馬原理

講一下SQL注入中寫一句話拿webshell的原理&#xff0c;主要使用的是 SELECT ... INTO OUTFILE 這個語句&#xff0c;下面是一個語句的例子:SELECT * INTO OUTFILE C:\log1.txt這樣就可以把查詢到的數據寫入到C盤的log1.txt這個文件里面。利用這個原理我們可以把PHP的一句話木馬…

開源貢獻 計算_使用此網站為開源做貢獻

開源貢獻 計算When I began the transition into being a software developer, I knew that contributing to open source projects would greatly assist my job search.當我開始過渡為軟件開發人員時&#xff0c;我知道為開源項目做貢獻將極大地幫助我的求職。 So, I jumped…

leetcode275. H指數 II(二分法)

給定一位研究者論文被引用次數的數組&#xff08;被引用次數是非負整數&#xff09;&#xff0c;數組已經按照升序排列。編寫一個方法&#xff0c;計算出研究者的 h 指數。 h 指數的定義: “h 代表“高引用次數”&#xff08;high citations&#xff09;&#xff0c;一名科研人…

java 多線程阻塞隊列 與 阻塞方法與和非阻塞方法

Queue是什么隊列&#xff0c;是一種數據結構。除了優先級隊列和LIFO隊列外&#xff0c;隊列都是以FIFO&#xff08;先進先出&#xff09;的方式對各個元素進行排序的。無論使用哪種排序方式&#xff0c;隊列的頭都是調用remove()或poll()移除元素的。在FIFO隊列中&#xff0c;所…

批量移動AD用戶到指定OU

作為域管理員&#xff0c;在日常工作中使用ADUC&#xff08;AD用戶和計算機&#xff09;工具在圖形界面中進行賬號管理操作可謂是家常便飯了。然而一個個增加、移動、刪除用戶&#xff0c;這樣操作有時真的夠煩&#xff0c;當管理大批量的賬戶時&#xff0c;重復操作浪費的時間…

vs 編譯說明

靜態編譯/MT&#xff0c;/MTD 是指使用libc和msvc相關的靜態庫(lib)。動態編譯&#xff0c;/MD&#xff0c;/MDd是指用相應的DLL版本編譯。其中字母含義 d&#xff1a;debug m&#xff1a;multi-threading(多線程) t&#xff1a;text代碼 d&#xff1a;dynamic(動態)…

python numeric_Python pandas.to_numeric函數方法的使用

pandas.to_numeric(arg, errorsraise, downcastNone) [source]將參數轉換為數字類型。默認返回dtype為float64或int64&#xff0c; 具體取決于提供的數據。使用downcast參數獲取其他dtype。請注意&#xff0c;如果傳入非常大的數字&#xff0c;則可能會導致精度損失。由…

javascript 分號_讓我們談談JavaScript中的分號

javascript 分號要使用它們&#xff0c;還是不使用它們… (To use them, or not to use them…) Semicolons in JavaScript divide the community. Some prefer to use them always, no matter what. Others like to avoid them.JavaScript中的分號分隔社區。 有些人更喜歡始終…

leetcode436. 尋找右區間(二分法)

給定一組區間&#xff0c;對于每一個區間 i&#xff0c;檢查是否存在一個區間 j&#xff0c;它的起始點大于或等于區間 i 的終點&#xff0c;這可以稱為 j 在 i 的“右側”。 對于任何區間&#xff0c;你需要存儲的滿足條件的區間 j 的最小索引&#xff0c;這意味著區間 j 有最…

python篇第6天【數據類型】

Python有五個標準的數據類型&#xff1a;Numbers&#xff08;數字&#xff09;String&#xff08;字符串&#xff09;List&#xff08;列表&#xff09;Tuple&#xff08;元組&#xff09;Dictionary&#xff08;字典&#xff09;Python數字數字數據類型用于存儲數值。他們是不…

如何確定Ionic是否適合您的項目

by Simon Grimm西蒙格里姆(Simon Grimm) 如何確定Ionic是否適合您的項目 (How to find out if Ionic is the right choice for your project) Ionic has been around for quite some years. With the latest release of version 4, it has become an even better option for d…

二維數組的查找 java_查找二維數組java的總和

我正在一個項目中&#xff0c;我必須讀取文件并將內容輸入2D數組。然后&#xff0c;我必須對每一行&#xff0c;每一列和矩陣的周長求和。到目前為止&#xff0c;除外圍功能外&#xff0c;我一切正常。我正在嘗試為兩個外部列的頂行&#xff0c;底行和中間創建單獨的for循環。矩…