使用.net核心Web API和jquery从天蓝色斑点中上传和检索图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用.net核心Web API和jquery从天蓝色斑点中上传和检索图像相关的知识,希望对你有一定的参考价值。

我正在尝试创建一个可以在其中发布带有图片的博客。基本上,我想做的是从本地计算机上选择图像,然后单击按钮以使用post方法将其发送到蔚蓝色斑点,然后使用get方法检索并在网页上显示图像。我找到了以下Microsoft文档:https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet但是我不知道如何将其应用于get和post方法。我也试过这个:

static void Main(string[] args)

string connStr = "your_connection_string_here";

CloudStorageAccount account = CloudStorageAccount.Parse(connStr);

CloudBlobClient client = account.CreateCloudBlobClient();

CloudBlobContainer container = client.
GetContainerReference("myblobcontainer");

container.CreateIfNotExists();

CloudBlockBlob blob = container.
GetBlockBlobReference("myblob");


blob.UploadFromFile(@"C:\Test\Image1.jpg");


但是我不知道如何将其应用于网络api。我有很多疑问,例如:1. get和post方法应该是什么?2.如何在get请求和post请求中使用jquery在客户端处理图像?3.如何通过put和get请求(可能是JSON)发送图像?4.如何将图像添加到img标签?5.如何识别哪个图像属于哪个帖子非常感谢您的帮助。如果我要问的内容不相关或无聊,请事先抱歉。我还是学生。注意:我正在使用.net core 2.1

答案

我将一个html页面作为客户端,作为.net核心api作为后端。尝试下面的代码:

1。客户端HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <title> 
        Async file upload with jQuery 
    </title> 

    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
</head> 

<body> 
    <div align="center"> 
        <form method="post" action="" enctype="multipart/form-data"
                id="myform"> 

            <div > 
                <input type="file" id="file" name="file" /> 
                <input type="button" class="button" value="Upload"
                        id="but_upload"> 
            </div> 
        </form> 

        </br>

        <div>
            <input type="button" id="but_display" value ="show all uploaded images">

            <div id="stage"></dev>

        </dev>
    </div>   

    <script type="text/javascript"> 
        $(document).ready(function()  
            $("#but_upload").click(function()  
                var fd = new FormData(); 
                var files = $('#file')[0].files[0]; 
                fd.append('file', files); 

                $.ajax( 
                    url: 'https://localhost:44348/api/blob/', 
                    type: 'post', 
                    data: fd, 
                    contentType: false, 
                    processData: false, 
                    success: function(response) 
                        if(response != 0) 
                        alert('file uploaded'); 
                         
                        else 
                            alert('file not uploaded'); 
                         
                    , 
                ); 
            );

            $("#but_display").click(function()  
                $.ajax( 
                    url: 'https://localhost:44348/api/blob/', 
                    type: 'get', 
                    success: function(response) 
                        $("#stage").empty();
                        response.forEach((url)=>

                            $("#stage").append("<img src='" + url +"' width='200' >");

                        )
                    
                );

            );
        ); 
    </script> 
</body> 

</html> 

2.backend .net core API:

1)。创建一个新的.net核心API项目。2)。转到Startup.csConfigureServices方法,粘贴下面的代码以替换它:

    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    ));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSingleton<CloudBlobClient>(sp =>  return CloudStorageAccount.Parse("<your storage account connection string>").CreateCloudBlobClient(); );

enter image description here

转到Configure方法。在下面添加一行代码:

app.UseCors("MyPolicy");

enter image description here

3)。转到Controller文件夹,使用以下代码创建控制器BlobController.cs

using System;
using System.Collections;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Storage.Blob;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace blobApitest


    [Route("api/[controller]")]
    [EnableCors("MyPolicy")]
    public class BlobController : Controller
    

        private CloudBlobClient cloudBlobClient;


        public BlobController(CloudBlobClient cloudBlobClient)
        
            this.cloudBlobClient = cloudBlobClient;

        

        [HttpPost()]
        public OkObjectResult upload([FromForm] IFormFile file)
        

           string FileName = file.FileName;
           var container = cloudBlobClient.GetContainerReference("<your container name>");
           var blob = container.GetBlockBlobReference(FileName);

           blob.UploadFromStream(file.OpenReadStream());

           return Ok("uploaded");
        

        [HttpGet()]

        public OkObjectResult GetAll() 

            var bloblist = new ArrayList();

            var container = cloudBlobClient.GetContainerReference("<your container name>");
            SharedAccessBlobPolicy ReadOnly = new SharedAccessBlobPolicy()
            
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                Permissions = SharedAccessBlobPermissions.Read
            ;

            var sas = container.GetSharedAccessSignature(ReadOnly);

            foreach (var blob in container.ListBlobs()) 
                bloblist.Add(blob.Uri+sas);
            
            return Ok(bloblist);
        

      

4)。运行该项目。

测试结果:

如果成功将imgae上传到存储,您将收到警报:enter image description here

让我们检查容器,图像已成功上传:enter image description here

单击显示所有图像按钮,将显示容器中的所有图像:enter image description here

希望有帮助。

以上是关于使用.net核心Web API和jquery从天蓝色斑点中上传和检索图像的主要内容,如果未能解决你的问题,请参考以下文章