How to upload an image and send it to the server, to the database, in bytes?
1 answer
Here is an example of my code:
uploadAvatar(e: any) { const fileReader = new FileReader(); const fileName = e.target.files[0].name; fileReader.onloadend = (e: any) => { this.avatar = fileReader.result; this.saveAvatar(this.dataURItoBlob(fileReader.result), fileName); } fileReader.readAsDataURL(e.target.files[0]); } saveAvatar(image: Blob, name: string) { this.userService.saveAvatar(image, name).subscribe(); } private dataURItoBlob(dataURI): Blob { var byteString = atob(dataURI.split(',')[1]); var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } var blob = new Blob([ab], { type: mimeString }); return blob; } uploadAvatar - hangs on (change) and then uses dataURItoBlob to apply dataURI to Blob, and then send it to the server via the service: the saveAvatar method. Service example:
saveAvatar(image, name ): Observable<any> { const formData = new FormData(); formData.append('avatar', image, name); return this.http.post(url, formData); } Sending to the server is done through POST from the HttpClient service, the first parameter is the URL, 2 is the instance of the FormData in which our image is added.
Code samples are made on Angular 5.2.3
|