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添加了新屬性:Pending和Status。 待定可以是false或true,具體取決于當前是否正在上傳圖像。 狀態是上傳過程的結果。 它可以是好還是失敗。
OnSuccess and onError are called after image upload and they set the status of an image.
上載圖像后調用OnSuccess和onError ,它們設置圖像的狀態。
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上傳圖片