Azure 存储,无法正确上传图片。

3
我正在尝试在mvc项目中创建一个动作,可以将文件和图片上传到我的Azure存储。但出于某种原因,它不能正确上传,这就是我猜测的原因。 如果我使用“Azure Storage Explorere”上传图像,则可以正常工作。 例如:http://storage.sogaard.us/company1/wallpaper-396234.jpg 但是,如果我尝试通过我的动作上传图像,它将无法正常工作,它会发送200以表示成功,并返回正确的内容类型,但是图像将无法加载,我的开发人员工具告诉我从服务器没有得到数据。 例如:http://storage.sogaard.us/company1/b9206edac188e1d8aa2b3be7cdc4b94a.jpg 我已经尝试将上传的文件保存到本地计算机而不是Azure存储中,它在那里运行良好!我只是找不到原因,这让我整天都很困扰:(
以下是我的代码:
[HttpPost]
public ActionResult Upload(FilesUploadModel model, IEnumerable<HttpPostedFileBase> files)
{

    if(ModelState.IsValid)
    {
        if (files != null && files.Any())
        {
            int maxSizeInBytes = ConfigurationManager.Instance.Configuration.FileMaxSize;
            Size thumbSize = new Size(200, 200);

            foreach (HttpPostedFileBase file in files.Where(x => x != null))
            {
                CMS.Common.Data.File _file = new Sogaard.Inc.CMS.Common.Data.File();

                // is any files uploadet?
                if (!(file.ContentLength > 0))
                {
                    FlashHelper.Add(Text("File not received"), FlashType.Error);
                    continue;
                }
                // is the file larger then allowed
                if (file.ContentLength > maxSizeInBytes)
                {
                    FlashHelper.Add(Text("The file {0}'s file size was larger then allowed", file.FileName), FlashType.Error);
                    continue;
                }

                var fileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now) + Path.GetExtension(file.FileName);
                string mimeType = FileHelper.MimeType(FileHelper.GetMimeFromFile(file.InputStream));

                _file.SiteId = SiteId();
                _file.Container = GetContainerName();
                _file.FileName = Path.GetFileName(file.FileName);
                _file.FileNameServer = fileName;
                _file.Created = DateTime.Now;
                _file.Folder = model.Folder;
                _file.Size = file.ContentLength;
                _file.Type = mimeType;

                if (mimeType.ToLower().StartsWith("image/"))
                {
                    try
                    {
                        // So we don't lock the file
                        using (Bitmap bitmap = new Bitmap(file.InputStream))
                        {
                            _file.Information = bitmap.Width + "|" + bitmap.Height;

                            if (bitmap.Height > 500 && bitmap.Width > 500)
                            {
                                var thumbfileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + "thumb" + DateTime.Now) + ".jpeg";
                                Size thumbSizeNew = BaseHelper.ResizeImage(bitmap.Size, thumbSize);
                                Bitmap thumbnail = (Bitmap)bitmap.GetThumbnailImage(thumbSizeNew.Width,
                                                                                          thumbSizeNew.Height,
                                                                                          ThumbnailCallback,
                                                                                          IntPtr.Zero);
                                _file.ThumbFileNameServer = thumbfileName;
                                // Retrieve reference to a blob named "myblob"
                                CloudBlob blob = container().GetBlobReference(_file.ThumbFileNameServer);
                                blob.Metadata["Filename"] = Path.GetFileNameWithoutExtension(file.FileName) + "-thumb" + ".jpg";
                                blob.Properties.ContentType = "image/jpeg";

                                // Create or overwrite the "myblob" blob with contents from a local file
                                using (MemoryStream memStream = new MemoryStream())
                                {
                                    thumbnail.Save(memStream, ImageFormat.Jpeg);
                                    blob.UploadFromStream(memStream);
                                }
                                blob.SetMetadata();
                                blob.SetProperties();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (e.GetType() != typeof (DataException))
                            FlashHelper.Add(Text("The image {0} was not a valid image", file.FileName),
                                            FlashType.Error);
                        // Removing the file
                        System.IO.File.Delete(file.FileName);
                    }
                }
                else
                {
                    _file.Information = null;
                }
                // Retrieve reference to a blob named "myblob"
                CloudBlob blobF = container().GetBlobReference(fileName);
                blobF.Metadata["Filename"] = file.FileName;
                blobF.Properties.ContentType = mimeType;

                // Create or overwrite the "myblob" blob with contents from a local file
                blobF.UploadFromStream(file.InputStream);
                blobF.SetMetadata();
                blobF.SetProperties();

                fileService.Save(_file);
            }
        }

        return RedirectToAction("Display", new { Folder = model.Folder });
    }

    model.FolderSugestion = fileService.GetFolders(SiteId());
    return View(model);
}

    private CloudBlobContainer container()
    {
        // Retrieve storage account from connection-string
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));

        // Create the blob client
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve reference to a previously created container
        var container = blobClient.GetContainerReference(GetContainerName());
        container.CreateIfNotExist();
        return container;
    }

    private string GetContainerName()
    {
        return "company" + SiteId();
    }
1个回答

1
在缩略图代码路径中,我认为您需要使用memStream.Position = 0将流重置到开头,然后再尝试上传它。
对于其他(非图像)代码路径,没有什么异常。那段代码有效吗?
在两个代码路径中,您不需要使用blob.SetMetadata()blob.SetProperties(),因为这些将在上传时完成。 [编辑]另外,GetMimeFromFile是做什么的?它是否从流中读取(因此可能会将流位置留在其他位置)?

初始化位图也会更改流的位置:new Bitmap(file.InputStream)。因此,在上传缩略图时重置memStream的位置之外,还应在调用此代码之前发生:blobF.UploadFromStream(file.InputStream)(上传实际文件时)。 - Sandrino Di Mattia
哦!我误读了条件语句的范围...你说得很对。 - user94559
到目前为止,我只测试了图像。GetMimeFromFile函数可以读取流。 - Androme
嘿,谢谢!这让我疯了!我也遇到了同样的问题,虽然我的代码略有不同(更基础...)。 - Dav.id

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接