32

When I upload an image file to a blob, the image is uploaded apparently successfully (no errors). When I go to cloud storage studio, the file is there, but with a size of 0 (zero) bytes.

The following is the code that I am using:

// 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));

Before the image file is uploaded to the storage, the Property InputStream from the HttpPostedFileBase appears to be fine (the size of the of image corresponds to what is expected! And no exceptions are thrown).

And the really strange thing is that this works perfectly in other cases (uploading Power Points or even other images from the Worker role). The code that calls the SetContent method seems to be exactly the same and file seems to be correct since a new file with zero bytes is created at the correct location.

Does any one have any suggestion please? I debugged this code dozens of times and I cannot see the problem. Any suggestions are welcome!

Thanks

4

2 回答 2

63

HttpPostedFileBase 的 InputStream 的 Position 属性与 Length 属性具有相同的值(可能是因为我在这个文件之前有另一个文件 - 我认为这很愚蠢!)。

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

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

于 2010-05-26T10:40:44.710 回答
32

感谢 Fabio 提出这个问题并解决了您自己的问题。我只想为您所说的添加代码。你的建议对我来说非常有效。

        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);

现在您可以使用以下命令上传 memoryStream:

blockBlob.UploadFromStream(memoryStream);
于 2016-08-05T07:26:54.080 回答