Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我上传到Azure的图像包含阻止显示的错误?_C#_Azure_Asp.net Core_Azure Blob Storage - Fatal编程技术网

C# 为什么我上传到Azure的图像包含阻止显示的错误?

C# 为什么我上传到Azure的图像包含阻止显示的错误?,c#,azure,asp.net-core,azure-blob-storage,C#,Azure,Asp.net Core,Azure Blob Storage,我已将图像上载到Azure中的blob存储帐户,每当我尝试通过web浏览器或Azure容器资源管理器访问这些图像时,我都会收到错误消息 无法显示图像“whatever.jpg”,因为它包含错误 它没有给我更多的信息,在Azure explorer中查看文件,我可以看到它的名称正确,具有正确的图像类型,具有数据,如我可以看到的字节 我查看了访问权限,并将容器文件夹设置为publicread access,不需要密钥。为了进一步测试错误,我通过azure dashboard将相同的图像直接上传到存储

我已将图像上载到Azure中的blob存储帐户,每当我尝试通过web浏览器或Azure容器资源管理器访问这些图像时,我都会收到错误消息

无法显示图像“whatever.jpg”,因为它包含错误

它没有给我更多的信息,在Azure explorer中查看文件,我可以看到它的名称正确,具有正确的图像类型,具有数据,如我可以看到的字节

我查看了访问权限,并将容器文件夹设置为public
read access
,不需要密钥。为了进一步测试错误,我通过azure dashboard将相同的图像直接上传到存储帐户,并且它们可以正常工作,因此问题一定是我上传它们的方式有问题

出于上下文的考虑,我在应用程序中使用blob存储服务,并在控制器中使用依赖项注入

创建

@model Car
<div class="row">
    <div class="col">
        <form asp-action="Create" asp-controller="Car" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col">
                    <div class="md-form form-group">
                        <label asp-for="Name"></label>
                        <input type="text" class="form-control" asp-for="Name" />
                    </div>
                    <div class="md-form form-group">
                        <label asp-for="ImageFile" class="active">Image</label>
                        <!-- Image Upload-->
                        <kendo-upload name="ImageFile" show-file-list="true">
                        </kendo-upload>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <hr />
                    <button type="submit" class="btn btn-success">Submit</button>
                    <button type="reset" class="btn btn-amber">Reset</button>
                </div>
            </div>
        </form>
    </div>
</div>
BlobStorageService.cs

private readonly ICarService _carService;
private readonly IWebHostEnvironment _env;
private readonly IConfiguration _configuration;

public CarController(
    IWebHostEnvironment env,
    ICarService carService,
    IConfiguration configuration)
{
    _carService = carService;
    _env = env;
    _configuration = configuration;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
        //
        //Create Car First
        _carService.InsertCar(car);

        //
        //Get the id if the car just created            
        int id = car.Id;

        //
        //If file data is there, prepare and upload to
        //blob storage.
        if (car.ImageFile != null)
        {
            string category = "car";
            var fileName = "car-image.jpg";
            byte[] fileData = new byte[car.ImageFile.Length];
            string mimeType = car.ImageFile.ContentType;                   

            BlobStorageService objBlobService = new BlobStorageService(_configuration.GetConnectionString("AzureStorage"));

                car.ImagePath = objBlobService.UploadFileToBlob(
                    category, 
                    id, 
                    fileName, 
                    fileData, 
                    mimeType);
            }                
            return RedirectToAction(nameof(Index));
        }
        return View(car);
    }
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace MyProject.Services
{
    public class BlobStorageService
    {
        string accessKey = string.Empty;        

        public BlobStorageService(string endPoint)
        {
            accessKey = endPoint;
        }

        public string UploadFileToBlob(string category, int id, string strFileName, byte[] fileData, string fileMimeType)
        {
            try
            {
                var _task = Task.Run(() => this.UploadFileToBlobAsync(category, id, strFileName, fileData, fileMimeType));
                _task.Wait();
                string fileUrl = _task.Result;
                return fileUrl;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async void GetBlobData(string id)
        { 
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

            string strContainerName = "uploads";
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);

            string pathPrefix = "car/" + id;
            CloudBlobDirectory blobDirectory = cloudBlobContainer.GetDirectoryReference(pathPrefix);

            // get block blob reference  
            CloudBlockBlob blockBlob = blobDirectory.GetBlockBlobReference("car-image.jpg");

            await blockBlob.FetchAttributesAsync();
        }          

        private async Task<string> UploadFileToBlobAsync(string category, int id, string strFileName, byte[] fileData, string fileMimeType)
        {
            try
            {
                string strContainerName = "uploads";
                string fileName = category + "/" + id + "/" + strFileName;

                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);
                CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();                
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);                

                if (await cloudBlobContainer.CreateIfNotExistsAsync().ConfigureAwait(false))
                {
                    await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }).ConfigureAwait(false);
                }

                if (fileName != null && fileData != null)
                {
                    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
                    cloudBlockBlob.Properties.ContentType = fileMimeType;
                    await cloudBlockBlob.UploadFromByteArrayAsync(fileData, 0, fileData.Length).ConfigureAwait(false);
                    return cloudBlockBlob.Uri.AbsoluteUri;
                }
                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}
使用Microsoft.WindowsAzure.Storage;
使用Microsoft.WindowsAzure.Storage.Blob;
使用制度;
使用System.IO;
使用System.Threading.Tasks;
使用Microsoft.Extensions.Configuration;
名称空间MyProject.Services
{
公共类BlobStorageService
{
string accessKey=string.Empty;
公共BlobStorageService(字符串端点)
{
accessKey=endPoint;
}
公共字符串UploadFileToBlob(字符串类别、int id、字符串strFileName、字节[]文件数据、字符串fileMimeType)
{
尝试
{
var_task=task.Run(()=>this.UploadFileToBlobAsync(category,id,strFileName,fileData,fileMimeType));
_task.Wait();
字符串fileUrl=\u task.Result;
返回fileUrl;
}
捕获(例外)
{
投掷;
}
}
公共异步void GetBlobData(字符串id)
{ 
CloudStorageAccount CloudStorageAccount=CloudStorageAccount.Parse(accessKey);
CloudBlobClient CloudBlobClient=cloudStorageAccount.CreateCloudBlobClient();
字符串strContainerName=“上传”;
CloudBlobContainer CloudBlobContainer=cloudBlobClient.GetContainerReference(strContainerName);
字符串pathPrefix=“car/”+id;
CloudBlobDirectory blobDirectory=cloudBlobContainer.GetDirectoryReference(路径前缀);
//获取块blob引用
CloudBlockBlob=blobDirectory.getblockblobbreference(“car image.jpg”);
等待blockBlob.FetchAttributesAsync();
}          
专用异步任务UploadFileToBlobAsync(字符串类别、int id、字符串strFileName、字节[]文件数据、字符串fileMimeType)
{
尝试
{
字符串strContainerName=“上传”;
字符串文件名=类别+“/”+id+“/”+strFileName;
CloudStorageAccount CloudStorageAccount=CloudStorageAccount.Parse(accessKey);
CloudBlobClient CloudBlobClient=cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer CloudBlobContainer=cloudBlobClient.GetContainerReference(strContainerName);
if(wait cloudBlobContainer.CreateIfNotExistsAsync().configurewait(false))
{
Wait cloudBlobContainer.SetPermissionsAsync(新BlobContainerPermissions{PublicAccess=BlobContainerPublicAccessType.Blob});
}
if(fileName!=null&&fileData!=null)
{
CloudBlockBlob CloudBlockBlob=cloudBlobContainer.getblockblobbreference(文件名);
cloudBlockBlob.Properties.ContentType=fileMimeType;
等待cloudBlockBlob.UploadFromByteArrayAsync(fileData,0,fileData.Length);
返回cloudBlockBlob.Uri.AbsoluteUri;
}
返回“”;
}
捕获(例外情况除外)
{
投掷(ex);
}
}
}
}

我能想到的唯一一件可能导致问题的事情是,文件类型(即jpg)是在字符串中定义的,而不是从上传的文件中获取的。上传的文件总是jpg,而且,接下来,图像将由第三方库进行处理,以便调整大小和转换(如果需要)。但是,作为一个测试,在字符串中包含文件类型似乎不是一个问题,但我将接受这方面的指导。

我在您的代码中看到的一个问题是,您只是初始化
fileData
数组,而不是用实际的文件字节填充它

byte[] fileData = new byte[car.ImageFile.Length];
实际上你上传的是一个所有字节都为零的文件


不知何故,您需要用用户上传的数据(图像)填充此数组。

我在您的代码中看到的一个问题是,您只是初始化
文件数据
数组,而不是用实际的文件字节填充它

byte[] fileData = new byte[car.ImageFile.Length];
实际上你上传的是一个所有字节都为零的文件


不知何故,您将需要使用用户上传的数据(图像)填充此数组。

如果您的car.ImageFile是ifformfile类型,您只需使用文件流上传图像,如下所示。问题是您正在上载一个空字节数组

using (var fileStream = car.ImageFile.OpenReadStream())
{
    await cloudBlockBlob.UploadFromStreamAsync(fileStream);
}
编辑:(在代码中)(注意:这只是一个想法,未经测试)

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
        //
        //Create Car First
        _carService.InsertCar(car);

        //
        //Get the id if the car just created            
        int id = car.Id;

        //
        //If file data is there, prepare and upload to
        //blob storage.
        if (car.ImageFile != null)
        {
            string category = "car";
            var fileName = "car-image.jpg";
            byte[] fileData = new byte[car.ImageFile.Length];
            string mimeType = car.ImageFile.ContentType;                   

            BlobStorageService objBlobService = new BlobStorageService(_configuration.GetConnectionString("AzureStorage"));
            using (var fileStream = car.ImageFile.OpenReadStream())
            {
                car.ImagePath = objBlobService.UploadFileToBlob(
                    category, 
                    id, 
                    fileName, 
                    fileStream, 
                    mimeType);
            }
            }                
            return RedirectToAction(nameof(Index));
        }
        return View(car);
    }
BlobStorageService.cs

    public string UploadFileToBlob(string category, int id, string strFileName, Stream fileStream, string fileMimeType)
    {
        try
        {
            var _task = Task.Run(() => this.UploadFileToBlobAsync(category, id, strFileName, fileStream, fileMimeType));
            _task.Wait();
            string fileUrl = _task.Result;
            return fileUrl;
        }
        catch (Exception)
        {
            throw;
        }
    }

    private async Task<string> UploadFileToBlobAsync(string category, int id, string strFileName, Stream fileStream, string fileMimeType)
    {
        try
        {
            string strContainerName = "uploads";
            string fileName = category + "/" + id + "/" + strFileName;

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(accessKey);
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();                
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(strContainerName);                

            if (await cloudBlobContainer.CreateIfNotExistsAsync().ConfigureAwait(false))
            {
                await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }).ConfigureAwait(false);
            }

            if (fileName != null && fileStream != null)
            {
                CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
                cloudBlockBlob.Properties.ContentType = fileMimeType;
                await cloudBlockBlob.UploadFromStreamAsync(fileStream).ConfigureAwait(false);
                return cloudBlockBlob.Uri.AbsoluteUri;
            }
            return "";
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
public string UploadFileToBlob(字符串类别、int-id、字符串strFileName、流fileStream、字符串fileMimeType)
{
尝试
{
var_task=task.Run(()=>this.UploadFileToBlobAsync(category,id,strFileName,fileStream,fileMimeType));
_task.Wait();
字符串文件