Answered by:
How to get a file (Image file - jpg/jpeg/png) from Azure blob storage and pass it to client application (angular 8/ typescript)?

Question
-
User944361600 posted
There are 2 tasks I'm trying to achieve,
- To upload a file t blob storage using web api.
- To retrieve the same file from blob storage from angular 8 client app and web api.
I was able to achieve the first task, but got stuck badly with the second task, I'm not sure of which way I can do that not I have any idea how to achieve the task. Below is the code I used to Upload and Get the image.
[HttpPost] [Route("updateuserprofileimage/{userguid}")] public HttpResponseMessage UpdateUserProfileImageByUserGuid(Guid userGuid) { try { var httpContext = HttpContext.Current.Request; if (httpContext.Files.Count == 0 || httpContext.Files[0].ContentLength == 0) { return Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid file, please check your file and try again."); } var context = new BuffiniCodeBehindBusinessLogicProfile(); string fileName = httpContext.Files[0].FileName; string contentType = httpContext.Files[0].ContentType; var result = context.UpdateUserProfileImageByUserGuid(httpContext.Files[0].InputStream, userGuid, fileName, contentType); return Request.CreateResponse(HttpStatusCode.OK, "Successfully uploaded."); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); throw ex; } } // Code behind logic public async Task UpdateUserProfileImageByUserGuid(Stream inputStream, Guid userGuid, string fileName, string contentType) { CloudStorageAccount ctxAdmin = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_BLOB_PROFILE_CONNECTION_STRING].ToString()); CloudBlobClient blobClient = ctxAdmin.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings[Constants.APP_SETTINGS_BLOB_CONTAINER_ISSUER].ToString()); container.CreateIfNotExists(); string extension = Path.GetExtension(fileName); string userGuidString = userGuid.ToString().ToLowerInvariant(); string newFileName = userGuidString + extension; try { var blockBlobs = container.ListBlobs(prefix: userGuidString).OfType<CloudBlockBlob>(); foreach (var blockBlob in blockBlobs) { blockBlob.DeleteIfExists(); } var blob = container.GetBlockBlobReference(newFileName); blob.Properties.ContentType = contentType; using (inputStream) { await blob.UploadFromStreamAsync(inputStream); } } catch(StorageException ex) { //ErrorSignal.FromCurrentContext().Raise(ex); throw ex; } }
Second task, getting the image:
[HttpGet] [Route("getuserprofileimage/{userguid}")] public async Task<HttpResponseMessage> GetUserProfileImageByUserGuid(Guid userGuid) { var context = new BuffiniCodeBehindBusinessLogicProfile(); CloudBlockBlob blockBlob = context.GetUserProfileImageByUserGuid(userGuid); var blockBlobExists = await blockBlob.ExistsAsync(); if (!blockBlobExists) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not found"); } blockBlob.FetchAttributes(); HttpResponseMessage model = new HttpResponseMessage(); //Stream blockBlobStream = await blockBlob.OpenReadAsync(); byte[] blockBlobByte = new byte[blockBlob.Properties.Length]; blockBlob.DownloadToByteArray(blockBlobByte,0); string contentType = blockBlob.Properties.ContentType; //string base64Byte = Convert.ToBase64String(blockBlobByte); //ByteArrayContent byteContent = new ByteArrayContent(blockBlobByte); //var imageBase64 = Convert.ToBase64String(blockBlobByte); model.Content = new ByteArrayContent(blockBlobByte); //model.Content.Headers.ContentLength = blockBlob.Properties.Length; model.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); //model.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") //{ // FileName = blockBlob.Name, // Size = blockBlob.Properties.Length //}; //, new MediaTypeHeaderValue(contentType) return Request.CreateResponse(HttpStatusCode.OK, model); } // Code behind file public CloudBlockBlob GetUserProfileImageByUserGuid(Guid userGuid) { CloudStorageAccount ctxAdmin = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_BLOB_PROFILE_CONNECTION_STRING].ToString()); CloudBlobClient blobClient = ctxAdmin.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings[Constants.APP_SETTINGS_BLOB_CONTAINER_ISSUER].ToString()); string fileName = userGuid.ToString().ToLower(); //CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); //var blobClient = storageAccount.CreateCloudBlobClient(); //var container = blobClient.GetContainerReference("images"); //container.CreateIfNotExists(); var blockBlobs = container.ListBlobs(prefix: fileName).OfType<CloudBlockBlob>(); CloudBlockBlob blockBlob = blockBlobs.First(); return blockBlob; }
Client app, Angular 8 - type script:
Client side code: //Service.ts getProfileImage(imageId: string): Observable<Blob> { //imageId: string + imageId return this.http.get(this.imageInfoUrl + imageId, { responseType: 'blob' }); } //component.ts this.isImageLoading = true; //"6B1ECEBA-4D3B-4598-A1FC-6B7B1D6D99D2" this.profileService.getProfileImage("6B1ECEBA-4D3B-4598-A1FC-6B7B1D6D99D2/").subscribe( data => { console.log("ananth"); this.createImageFromBlob(data); this.isImageLoading = false; console.log(data); }, error => { this.isImageLoading = false; this.errorMessage = <any>error; } ); createImageFromBlob(image: Blob) { const reader = new FileReader(); reader.onload = () => { console.log(reader.result); this.imageToShow = reader.result; console.log('ananth2'); }; if (image) { console.log('ananth3'); reader.readAsDataURL(image); } }
// Html div<div> <div>
<div class="image"> <!-- <img class="btn-md" src="assets/images/default.png" alt="" style="border-radius:50%;"> --> <img class="btn-md" [src]="imageToShow" alt="" *ngIf="!isImageLoading; else noImageFound" style="border-radius:50%;"> <div class="file btn"> <input type="file" name="file" /> </div> </div>
Pardon me if I have committed any mistakes, because I'm pretty new to angular 8 and this type of situation.
Kindly help me out, how to get this task done. I appreciate any help. Thanks
Wednesday, August 7, 2019 1:21 AM
Answers
-
User944361600 posted
Thanks for the response Brando, I appreciate your time.
I have posted the same question in another forum and after lot of approaches, I was able to find the solution.
Here is the link,
Thanks again.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, August 8, 2019 3:02 PM
All replies
-
User283571144 posted
Hi ananthasamani,
Pardon me if I have committed any mistakes, because I'm pretty new to angular 8 and this type of situation.
Kindly help me out, how to get this task done. I appreciate any help. Thanks
According to your description and codes, I found you use the Request.CreateResponse(HttpStatusCode.OK, model) to create the response.
If you use this method, it will not add the image byte content as the response content. It will generate a json result instead of the image content.
I suggest you could directly ruturn the model as the response instead of creating again.
More details, you could refer to below codes:
[HttpGet] [Route("getuserprofileimage/{userguid}")] public async Task<HttpResponseMessage> GetUserProfileImageByUserGuid(Guid userGuid) { CloudStorageAccount ctxAdmin = CloudStorageAccount.Parse(" aaaa"); CloudBlobClient blobClient = ctxAdmin.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("uploads"); string fileName = userGuid.ToString().ToLower(); //CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); //var blobClient = storageAccount.CreateCloudBlobClient(); //var container = blobClient.GetContainerReference("images"); //container.CreateIfNotExists(); var blockBlobs = container.ListBlobs(prefix: fileName).OfType<CloudBlockBlob>(); CloudBlockBlob blockBlob = blockBlobs.First(); var blockBlobExists = await blockBlob.ExistsAsync(); if (!blockBlobExists) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not found"); } blockBlob.FetchAttributes(); HttpResponseMessage model = new HttpResponseMessage(); //Stream blockBlobStream = await blockBlob.OpenReadAsync(); byte[] blockBlobByte = new byte[blockBlob.Properties.Length]; blockBlob.DownloadToByteArray(blockBlobByte, 0); string contentType = blockBlob.Properties.ContentType; //string base64Byte = Convert.ToBase64String(blockBlobByte); //ByteArrayContent byteContent = new ByteArrayContent(blockBlobByte); //var imageBase64 = Convert.ToBase64String(blockBlobByte); model.Content = new ByteArrayContent(blockBlobByte); //model.Content.Headers.ContentLength = blockBlob.Properties.Length; model.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); //model.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") //{ // FileName = blockBlob.Name, // Size = blockBlob.Properties.Length //}; //, new MediaTypeHeaderValue(contentType) return model; }
Result:
Best Regards,
Brando
Thursday, August 8, 2019 9:32 AM -
User944361600 posted
Thanks for the response Brando, I appreciate your time.
I have posted the same question in another forum and after lot of approaches, I was able to find the solution.
Here is the link,
Thanks again.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, August 8, 2019 3:02 PM -
User283571144 posted
Hi ananthasamani,
I'm glad that you have found the solution by yourself, I suggest you could try to mark the right reply as the answer.
It will make other folks who faces the same issue will find the answer more easily .
Thank you.
Best Regards,
Brando
Monday, August 12, 2019 1:54 AM