【问题标题】:Upload the image into storage blob using typescript and angular2使用 typescript 和 angular2 将图像上传到存储 blob
【发布时间】:2016-12-06 20:58:34
【问题描述】:

我正在使用 typescript 开发 Angular 2 应用程序。在我当前的项目中,我实现了将图像上传到 azure 存储 blob 的功能,为此我点击了以下链接。

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

我为视图编写以下代码行,以从本地计算机中选择图像。

<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>     

我的视图将如下图所示。

当我点击上传按钮时,在 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 文件中,我编写了以下代码行,用于将图像上传到 azure 存储 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;
        }



    }

在上面的控制器代码中,下面的代码总是给出空值。

var image = WebImage.GetImageFromRequest();

你能告诉我如何解决上述问题。

-Pradeep

【问题讨论】:

    标签: angular typescript azure-blob-storage


    【解决方案1】:

    经过大量研究,我得到了结果。以下链接对于将所选图像上传到服务器或 Azure 存储 blob 非常有用。对于我的场景,我已将选定的图像上传到 azure 存储 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 的功能有所帮助。

    问候,

    普雷迪普

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 2020-01-09
      • 2014-07-22
      • 2020-02-23
      • 2014-05-22
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多