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

2024-02-05

我正在使用打字稿开发 Angular 2 应用程序。在我当前的项目中,我实现了将图像上传到天蓝色存储 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

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

<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. enter image description here

当我单击“上传”按钮时,在上传组件.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')
            );


    }

上传图像控制器.cs

In the 上传图像控制器.cs文件我写了下面几行代码,用于将图像上传到天蓝色存储 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


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

这是我的上传图片.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>

这是我的上传图片.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;
    }

这是我的上传图像控制器.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 应用程序中使用 TypeScript 将所选图像上传到 Azure 存储 Blob 的功能的人有所帮助。

Regards,

Pradeep

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 typescript 和 angular2 将图像上传到存储 blob 的相关文章

随机推荐

  • urlManager 在 Yii 2.0 中不工作

    我正在尝试学习 yii 2 0 目前我正在使用basicyii 2 0 版本 第一步是配置 url 所以根据指南 我启用了mod rewrite 使用检查它phpinfo 然后在中添加以下行components of config web
  • 将 'yyyymmdd hhmmss' 转换为 'mm/dd/yy hh:mm'

    我有一行数据 单元格 A3 及以下 其中包含 Unix 时间戳yyyymmdd hhmmss我试图转换成的格式mm dd yy hh mm format 自动地 当我的数据从单元格 A1 开始时 到目前为止 我的代码可以工作 但我需要 A1
  • 如何在集合获取中保留自定义属性

    我有一个 资产 骨干模型 它有一个名为 选定 的自定义属性 它是自定义的 因为它不是服务器端对象的一部分 我用它来表示用户当前选择的资产列表中的哪一个 var Asset Backbone Model extend defaults sel
  • 从 Spring Boot 应用程序运行 KSQL 的方式是什么

    我有一个连接到 kafka 集群的 Spring Boot 应用程序 如何从 java 代码运行 KSQL 目前 还没有直接的方法在java中使用KSQL作为库 有一个开放的问题 734 https github com confluent
  • Highcharts TypeScript,y 轴标签

    请参考讨论Highcharts y 轴文本标签 https stackoverflow com questions 4987457 highcharts text labels for y axis设置y轴标签的方法 I used http
  • GWT UiBinder 和图像精灵

    我无法让 CSS 图像精灵出现在 GWT UiBinder 中 我做了评论如何在 GWT 中使用图像精灵 https stackoverflow com questions 4535094 how do i use image sprite
  • 如何创建与环境无关的 JavaScript 库

    我正在创建一个 javascript 库 我希望它与环境无关 它不会使用 DOM AJAX 或 NodeJS api 它将是普通的 javascript 因此 它应该可以在任何 javascript 环境中运行 浏览器 npm meteor
  • 12因素应用程序存储配置的过程是什么?

    所以我一直将我的应用程序主要构建为 12 因素应用程序 现在查看配置部分 目前 我有用于开发和生产的单独配置文件 通过构建过程 我们可以构建开发或生产映像 代码 100 相同 唯一改变的是配置 现在我 100 明白 在 12 因素应用程序中
  • C++中iostream头的cout、cerr、clog有什么区别?什么时候使用哪一个?

    我尝试研究之间的区别cout cerr and clog在互联网上但找不到完美的答案 我仍然不清楚何时使用哪个 谁能通过简单的程序向我解释并说明何时使用哪个程序的完美情况 我参观过这个网站 http www tutorialspoint c
  • 嵌套向量与连续数组的性能影响

    是否有任何可靠的测试可以清楚地显示访问和写入嵌套向量与 C 内置数组之间的性能差异 我听说 与访问单个数组中的元素 所有元素都存储在连续的内存中 相比 使用嵌套 多维 向量通常会产生一些性能开销 但这对我来说似乎都是假设的 我还没有看到任何
  • Blazor 启动错误:System.Threading.SynchronizationLockException:无法在此运行时上等待监视器

    我试图在 blazor 客户端 启动期间调用 api 将语言翻译加载到 ILocalizer 中 此时 我尝试从获取请求中获取 Result blazor 会在标题中抛出错误 这可以通过在program cs中调用此方法来复制 privat
  • Socket.io 不在 /socket.io/socket.io.js 中提供服务

    我已经在这里阅读了有关我的 node js 问题的答案 但我的问题仍然存在 在服务器中使用socket io 一切看起来都正常 但在客户端 chrome 说 无法加载资源 服务器响应状态为 404 未找到 本地主机 3382 so cket
  • 两个向量的欧氏距离

    如何找到两个向量的欧几里得距离 x1 lt rnorm 30 x2 lt rnorm 30 Use the dist 函数 但您需要根据第一个参数的两个输入形成一个矩阵dist dist rbind x1 x2 对于OP问题中的输入 我们得
  • eclipse远程调试超时问题

    当我尝试连接到本地计算机上的远程服务器 jboss 时 一切工作正常 但是如果我尝试连接到远程计算机 再次连接到jboss Eclipse 就会开始连接 并在一段时间后告诉我 Failed to connect to remote VM C
  • 空文件构造函数既不是文件也不是目录

    以下两种创建文件的方法有什么区别 new File System getProperty user dir new File Java 将第一个识别为目录 第二个识别为目录既不是文件也不是目录 为什么会这样 Code public clas
  • MVC 3模型foreach过滤器

    我有以下剃刀语法 foreach var p in Model b p Age b 我想过滤 foreach 循环以仅查看 p City New York 的模型记录 我的语法会是什么样子 我希望我能正确解释这一点 Thanks forea
  • 在 iOS8 中:UIPopoverController PresentPopoverFromRect 不再适用于 keyWindow

    如标题所示 在 iOS8 中 UIPopoverControllerpresentPopoverFromRect 不再适用于 UIApplicationsharedApplication keyWindow iOS7下确实可以用 我验证了以
  • DB2 SQL 中的正则表达式

    除了使用 UDF 是否有对 DB2 9 7 的 REGEXP In SQL 支持 从 DB2 11 1 开始 有内置的正则表达式支持 其中一项新功能是REGEXP SUBSTR http www ibm com support knowle
  • 如何更改大屏幕的背景颜色?

    我想知道如何更改 jumbotron 类的背景颜色 它有一个默认值background color eee在 bootstrap css 中 我试图通过删除它并给出属性来覆盖none none important transparent进入
  • 使用 typescript 和 angular2 将图像上传到存储 blob

    我正在使用打字稿开发 Angular 2 应用程序 在我当前的项目中 我实现了将图像上传到天蓝色存储 blob 的功能 为此我点击了以下链接 http www ojdevelops com 2016 05 end to end image