简体   繁体   English

使用typescript和angular2将图像上传到存储blob

[英]Upload the image into storage blob using typescript and angular2

I am developing angular 2 application using typescript. 我正在使用打字稿开发角度2应用程序。 in my current project I implemented the functionality for uploading image into azure storage blob, for that I followed the below link. 在我目前的项目中,我实现了将图像上传到azure存储blob的功能,为此我按照下面的链接。

http://www.ojdevelops.com/2016/05/end-to-end-image-upload-with-azure.html http://www.ojdevelops.com/2016/05/end-to-end-image-upload-with-azure.html

I write the below lines of code for my view to select the image from my local machine. 我为我的视图编写下面的代码行,从本地机器中选择图像。

<form name="form" method="post">
            <div class="input-group">

                <input id="imagePath" class="form-control" type="file" name="file" accept="image/*" />

                <span class="input-group-btn">

                    <a  class="btn btn-success" (click)='uploadImage()'>Upload</a>
                    <!--href="../UploadImage/upload"-->
                    <!--(click)='uploadImage()'-->
                </span>
            </div>               
        </form>     

My view will be like this below figure. 我的观点如下图所示。 在此输入图像描述

when I click Upload button, in the uploadcomponent.ts file I write the below lines of code for making http post request along with content as selected image path. 当我点击上传按钮时,在uploadcomponent.ts文件中,我编写了以下代码行,用于发送http post请求以及内容作为选定的图像路径。

        uploadImage(): void {



            //var image = Request["imagePath"];
            //alert('Selected Image Path :' + image);

            this.imagePathInput = ((<HTMLInputElement>document.getElementById("imagePath")).value);
            alert('Selected Image Path :' + this.imagePathInput);


           let imagePath = this.imagePathInput;

           var headers = new Headers();
           headers.append('Content-Type', 'application/x-www-form-urlencoded');//application/x-www-form-urlencoded

           this._http.post('/UploadImage/UploadImagetoBlob', JSON.stringify(imagePath),
            {
               headers: headers
            })
            .map(res => res.json())
            .subscribe(
            data => this.saveJwt(data.id_token),
            err => this.handleError(err),
            () => console.log('ImageUpload Complete')
            );


    }

UploadImageController.cs UploadImageController.cs

In the UploadImageController.cs file I write below lines of code for upload the image into azure storage blob. UploadImageController.cs文件中,我在下面写下代码行,将图像上传到azure storage blob。

    [HttpPost]
    [Route("UploadImage/UploadImagetoBlob")]
    public async Task<HttpResponseMessage> UploadImagetoBlob()
    {
        try
        {
            //WebImage image = new WebImage("~/app/assets/images/AzureAppServiceLogo.png");
            //image.Resize(250, 250);
            //image.FileName = "AzureAppServiceLogo.png";
            //img.Write();
            var image = WebImage.GetImageFromRequest();
            //WebImage image = new WebImage(imagePath);
            var imageBytes = image.GetBytes();

            // The parameter to the GetBlockBlobReference method will be the name
            // of the image (the blob) as it appears on the storage server.
            // You can name it anything you like; in this example, I am just using
            // the actual filename of the uploaded image.
            var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
            blockBlob.Properties.ContentType = "image/" + image.ImageFormat;

            await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);

            var response = Request.CreateResponse(HttpStatusCode.Moved);
            response.Headers.Location = new Uri("../app/upload/uploadimagesuccess.html", UriKind.Relative);
            //return Ok();
            return response;

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return null;
        }



    }

In the above controller code, the below line code always gives null value. 在上面的控制器代码中,下面的行代码总是给出空值。

var image = WebImage.GetImageFromRequest();

Can you please tell me how to resolve the above issue. 你能告诉我如何解决上述问题吗?

-Pradeep -Pradeep

After did a lot of research I got the result. 经过大量研究后,我得到了结果。 The below links are very useful for uploading the selected image into server or Azure storage blob. 以下链接对于将所选图像上载到服务器或Azure存储blob非常有用。 For my scenario I was uploaded selected image into azure storage blob. 对于我的场景,我将选定的图像上传到azure存储blob中。

https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/ https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/

http://www.ojdevelops.com/2016/05/end-to-end-image-upload-with-azure.html http://www.ojdevelops.com/2016/05/end-to-end-image-upload-with-azure.html

This is my UploadImage.Component.html 这是我的UploadImage.Component.html

<form name="form" method="post" action="" enctype="multipart/form-data">
<div class="input-group">

    <input id="imagePath" class="form-control" type="file" (change)="fileChangeEvent($event)" name="Image" accept="image/*" />

    <span class="input-group-btn">

        <a class="btn btn-success" (click)='uploadImagetoStorageContainer()'>Upload</a>

    </span>
</div>

This is my UploadImage.Component.ts 这是我的UploadImage.Component.ts

    /////////////////////////////////////////////////////////////////////////////////////
    // calling UploadingImageController using Http Post request along with Image file
    //////////////////////////////////////////////////////////////////////////////////////
    uploadImagetoStorageContainer() {
        this.makeFileRequest("/UploadImage/UploadImagetoBlob", [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
            });

    }
    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            var formData: any = new FormData();
            var xhr = new XMLHttpRequest();
            for (var i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        alert("successfully uploaded image into storgae blob");
                        resolve(JSON.parse(xhr.response));

                    } else {
                        reject(xhr.response);
                    }
                }
            }
            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }

    fileChangeEvent(fileInput: any) {
        this.filesToUpload = <Array<File>>fileInput.target.files;
    }

This is my UploadImageController.ts 这是我的UploadImageController.ts

    [HttpPost]
    [Route("UploadImage/UploadImagetoBlob")]
    public async Task<IHttpActionResult> UploadImagetoBlob()//string imagePath
    {
        try
        {
            //var iamge= imagePath as string;
            //WebImage image = new WebImage("~/app/assets/images/AzureAppServiceLogo.png");
            //image.Resize(250, 250);
            //image.FileName = "AzureAppServiceLogo.png";
            //img.Write();
            var image =WebImage.GetImageFromRequest();
            //WebImage image = new WebImage(imagePath);
            //var image = GetImageFromRequest();
            var imageBytes = image.GetBytes();

            // The parameter to the GetBlockBlobReference method will be the name
            // of the image (the blob) as it appears on the storage server.
            // You can name it anything you like; in this example, I am just using
            // the actual filename of the uploaded image.
            var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
            blockBlob.Properties.ContentType = "image/" + image.ImageFormat;

            await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);

            //var response = Request.CreateResponse(HttpStatusCode.Moved);
            //response.Headers.Location = new Uri("../app/upload/uploadimagesuccess.html", UriKind.Relative);
            //return response;
            return Ok();


        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return null;
        }

    }

This answer may be helpful for who are looking the functionality of uploading selected image into azure storage blob using typescript in angular 2 application. 这个答案可能有助于谁正在寻找使用角度2应用程序中的typescript将所选图像上传到azure存储blob的功能。

Regards, 问候,

Pradeep 普拉迪普

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM