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.
這是關(guān)于如何將圖像上傳到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.
您也可以觀看有關(guān)圖像上傳的分步視頻教程。 該鏈接位于本文的底部。
1.首先創(chuàng)建一個(gè)模板 (1. Create a template first)
First, we want to create a reusable component that will be easily pluggable into other components.
首先,我們要?jiǎng)?chuàng)建一個(gè)可重用的組件,該組件可輕松插入其他組件。
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.
讓我們從一個(gè)簡(jiǎn)單HTML模板開始輸入。 不要忘記應(yīng)用您選擇的樣式,或者您可以從我的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.
這里重要的是一種輸入類型 ,它被設(shè)置為文件。 Accept屬性定義接受的文件以供輸入。 Image / *指定我們可以通過(guò)此輸入選擇任何類型的圖像。 #imageInput是輸入的參考,我們可以在該參考上訪問(wèn)上載的文件。
A Change event is fired when we select a file. So let’s take a look at the class code.
當(dāng)我們選擇一個(gè)文件時(shí),將觸發(fā)一個(gè)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中看到 我們收到了來(lái)自change事件發(fā)送的圖像輸入。 通過(guò)寫入imageInput.files [0],我們可以訪問(wèn)第一個(gè)文件 。 我們需要閱讀器才能訪問(wèn)文件的其他屬性。 通過(guò)調(diào)用readAsDataURL,我們可以在之前訂閱的addEventListener的回調(diào)函數(shù)中獲得圖像的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.
在回調(diào)函數(shù)中,我們正在創(chuàng)建ImageSnippet的實(shí)例。 第一個(gè)值是我們稍后將在屏幕上顯示的圖像的base64表示形式。 第二個(gè)值是文件本身,我們將其發(fā)送到服務(wù)器以上傳到Amazon S3。
Now, we just need to provide this file and send a request through a service.
現(xiàn)在,我們只需要提供此文件并通過(guò)服務(wù)發(fā)送請(qǐng)求即可。
3.我們也需要服務(wù) (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.
沒(méi)有服務(wù)就不會(huì)是Angular應(yīng)用。 該服務(wù)將負(fù)責(zé)向我們的節(jié)點(diǎn)服務(wù)器發(fā)送請(qǐng)求。
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.
正如我在上一講中告訴您的那樣,我們需要將圖像作為表單數(shù)據(jù)的一部分發(fā)送。 我們將圖像添加圖像的項(xiàng)下,形成的數(shù)據(jù)(相同的密鑰我們之前配置的節(jié)點(diǎn))。 最后,我們只需要使用有效載荷中的formData向服務(wù)器發(fā)送請(qǐng)求。
Now we can celebrate. That’s it! Image sent to upload!
現(xiàn)在我們可以慶祝。 而已! 圖片已上傳!
In the next lines, I will provide some additional code for a better user experience.
在接下來(lái)的幾行中,我將提供一些額外的代碼以提供更好的用戶體驗(yàn)。
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添加了新屬性:Pending和Status。 待定可以是false或true,具體取決于當(dāng)前是否正在上傳圖像。 狀態(tài)是上傳過(guò)程的結(jié)果。 它可以是好還是失敗。
OnSuccess and onError are called after image upload and they set the status of an image.
上載圖像后調(diào)用OnSuccess和onError ,它們?cè)O(shè)置圖像的狀態(tài)。
Ok, now let’s take a look at the updated template file:
好的,現(xiàn)在讓我們看一下更新的模板文件:
<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.
在這里,我們根據(jù)圖像的狀態(tài)在屏幕上顯示上傳的圖像和錯(cuò)誤。 當(dāng)圖像待處理時(shí),我們還將顯示一個(gè)漂亮的旋轉(zhuǎn)圖像,以通知用戶上傳活動(dòng)。
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.
樣式不是本教程的重點(diǎn),因此您可以在此鏈接中獲得所有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.
任務(wù)完成! :)就應(yīng)該是一個(gè)簡(jiǎn)單的圖像上傳。 如果不清楚,請(qǐng)確保您首先觀看了本教程的第一部分。
If you like this tutorial, feel free to check my full course on Udemy — The Complete Angular, React & Node Guide | Airbnb style app.
如果您喜歡本教程,請(qǐng)隨時(shí)查看有關(guān)Udemy的完整課程- 《完整的Angular,React和Node指南》。 Airbnb風(fēng)格的應(yīng)用程序 。
Completed Project: My GitHub repository
完成的項(xiàng)目: 我的GitHub存儲(chǔ)庫(kù)
Video Lecture: YouTube Tutorial
視頻講座 : YouTube教程
Cheers,
干杯,
Filip
菲利普
翻譯自: https://www.freecodecamp.org/news/how-to-make-image-upload-easy-with-angular-1ed14cb2773b/
angular上傳圖片
總結(jié)
以上是生活随笔為你收集整理的angular上传图片_如何使用Angular轻松上传图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 梦到买漂亮衣服是什么意思
- 下一篇: 梦到梨和枣什么预兆