加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – 移植到MVC4后,Windows Azure UploadFromStream

发布时间:2020-12-16 06:26:15 所属栏目:asp.Net 来源:网络整理
导读:将我的MVC3 / .Net 4.5 / Azure解决方案更新为MVC4. 在升级的MVC4解决方案中,我每次将图像上传到blob存储的代码似乎都失败了.但是,当我运行我的MVC3解决方案工作正常.在DLL中进行上载的代码没有改变. 我在MVC3和MVC4解决方案中上传了相同的图像文件.我在溪流
将我的MVC3 / .Net 4.5 / Azure解决方案更新为MVC4.
在升级的MVC4解决方案中,我每次将图像上传到blob存储的代码似乎都失败了.但是,当我运行我的MVC3解决方案工作正常.在DLL中进行上载的代码没有改变.

我在MVC3和MVC4解决方案中上传了相同的图像文件.我在溪流中检查过,看起来很好.在这两个实例中,我在我的机器上本地运行代码,我的连接指向云中的blob存储.

有没有调试指针?升级到MVC4时我可能不知道的任何已知问题?
这是我的上传代码:

public string AddImage(string pathName,string fileName,Stream image)
    {
        var client = _storageAccount.CreateCloudBlobClient();
        client.RetryPolicy = RetryPolicies.Retry(3,TimeSpan.FromSeconds(5));
        var container = client.GetContainerReference(AzureStorageNames.ImagesBlobContainerName);

        image.Seek(0,SeekOrigin.Begin);
        var blob = container.GetBlobReference(Path.Combine(pathName,fileName));
        blob.Properties.ContentType = "image/jpeg";

        blob.UploadFromStream(image);

        return blob.Uri.ToString();
    }

解决方法

我设法修复它.出于某种原因,直接从HttpPostFileBase读取流不起作用.只需将其复制到新的内存流中即可解决问题.
我的代码

public string StoreImage(string album,HttpPostedFileBase image)
    {   
        var blobStorage = storageAccount.CreateCloudBlobClient();
        var container = blobStorage.GetContainerReference("containerName");
        if (container.CreateIfNotExist())
        {
            // configure container for public access
            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);
        }

        string uniqueBlobName = string.Format("{0}{1}",Guid.NewGuid().ToString(),Path.GetExtension(image.FileName)).ToLowerInvariant();
        CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
        blob.Properties.ContentType = image.ContentType;
        image.InputStream.Position = 0;
        using (var imageStream = new MemoryStream())
        {
            image.InputStream.CopyTo(imageStream);
            imageStream.Position = 0;
            blob.UploadFromStream(imageStream);
        }

        return blob.Uri.ToString();           
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读