使用打字稿和angular2将图像上传到存储Blob [英] Upload the image into storage blob using typescript and angular2

查看:70
本文介绍了使用打字稿和angular2将图像上传到存储Blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用打字稿开发angular 2应用程序.在我当前的项目中,我实现了将图像上传到Azure存储Blob的功能,为此,我点击了以下链接.

I am developing angular 2 application using typescript. in my current project I implemented the functionality for uploading image into azure storage blob, for that I followed the below link.

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.

当我单击上传"按钮时,在 uploadcomponent.ts 文件中,我编写了以下代码行,以进行http发布请求以及作为选定图像路径的内容.

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.

        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 文件中,我编写了以下几行代码,用于将图像上传到Azure存储Blob.

In the UploadImageController.cs file I write below lines of code for upload the image into 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

推荐答案

经过大量研究,我得到了结果.以下链接对于将所选图像上传到服务器或Azure存储Blob非常有用.对于我的情况,我将选定的图像上传到了Azure存储Blob.

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. For my scenario I was uploaded selected image into azure storage blob.

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

这是我的 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>

这是我的 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;
    }

这是我的 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;
        }

    }

对于正在寻找使用angular 2应用程序中的打字稿将所选图像上传到azure存储blob中的功能的人员,此答案可能会有所帮助.

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.

此致

Pradeep

这篇关于使用打字稿和angular2将图像上传到存储Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆