代码之家  ›  专栏  ›  技术社区  ›  Fabio Milheiro

Azure存储:上载的文件大小为零字节

  •  23
  • Fabio Milheiro  · 技术社区  · 15 年前

    当我将图像文件上载到blob时,图像显然已成功上载(没有错误)。当我进入CloudStorageStudio时,文件就在那里,但大小为0(零)字节。

    以下是我使用的代码:

    // These two methods belong to the ContentService class used to upload
    // files in the storage.
    public void SetContent(HttpPostedFileBase file, string filename, bool overwrite)
    {
        CloudBlobContainer blobContainer = GetContainer();
        var blob = blobContainer.GetBlobReference(filename);
    
        if (file != null)
        {
            blob.Properties.ContentType = file.ContentType;
            blob.UploadFromStream(file.InputStream);
        }
        else
        {
            blob.Properties.ContentType = "application/octet-stream";
            blob.UploadByteArray(new byte[1]);
        }
    }
    
    public string UploadFile(HttpPostedFileBase file, string uploadPath)
    {
        if (file.ContentLength == 0)
        {
            return null;
        }
    
        string filename;
        int indexBar = file.FileName.LastIndexOf('\\');
        if (indexBar > -1)
        {
            filename = DateTime.UtcNow.Ticks + file.FileName.Substring(indexBar + 1);
        }
        else
        {
            filename = DateTime.UtcNow.Ticks + file.FileName;
        }
        ContentService.Instance.SetContent(file, Helper.CombinePath(uploadPath, filename), true);
        return filename;
    }
    
    // The above code is called by this code.
    HttpPostedFileBase newFile = Request.Files["newFile"] as HttpPostedFileBase;
    ContentService service = new ContentService();
    blog.Image = service.UploadFile(newFile, string.Format("{0}{1}", Constants.Paths.BlogImages, blog.RowKey));
    

    在将图像文件上载到存储之前,来自httpPostedFileBase的属性inputstream似乎很好(图像的大小与预期的大小相对应!)不会抛出异常)。

    而真正奇怪的是,这在其他情况下(从工作者角色上传功率点,甚至其他图像)也能很好地工作。调用setcontent方法的代码似乎完全相同,并且文件似乎是正确的,因为在正确的位置创建了一个零字节的新文件。

    有人有什么建议吗?我调试了这段代码很多次,但看不到问题所在。欢迎提出任何建议!

    谢谢

    2 回复  |  直到 6 年前
        1
  •  48
  •   Fabio Milheiro    15 年前

    httpPostedFileBase的inputstream的position属性与length属性具有相同的值(可能是因为在此之前我有另一个文件-我认为这很愚蠢!).

    我所要做的就是将position属性设置回0(零)!

    我希望这对将来的人有帮助。

        2
  •  22
  •   Blaze    8 年前

    感谢法比奥提出并解决了你自己的问题。我只想把代码添加到你所说的内容中。你的建议对我很有效。

            var memoryStream = new MemoryStream();
    
            // "upload" is the object returned by fine uploader
            upload.InputStream.CopyTo(memoryStream);
            memoryStream.ToArray();
    
    // After copying the contents to stream, initialize it's position
    // back to zeroth location
    
            memoryStream.Seek(0, SeekOrigin.Begin);
    

    现在,您可以使用以下方法上载内存流:

    blockBlob.UploadFromStream(memoryStream);
    
    推荐文章