4

I have a simple app where I'm doing a form post with a file type input to a WCF Service. I'm trying to upload that file from the form post to an Azure blob and then download it by hitting the appropriate blob url.

What's happening now is I'm uploading a file to Azure but when I download it the file doesn't contain content. For instance if I upload something.zip or something.gif I can download it from the url but they both won't contain anything.

I've read that this could be because the position of the stream is not set to 0. It won't let me set the position of the Stream "stream" below so I copied it to a memoryStream. Sadly that didn't resolve the issue.

[OperationContract]
[WebInvoke(Method = "POST",
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "Upload")]
public string upload(Stream stream)
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(exerciseContainer);
    CloudBlob blob = container.GetBlobReference("myblob");

    Stream s = new MemoryStream();
    stream.CopyTo(s);
    s.Seek(0, SeekOrigin.Begin);
    blob.UploadFromStream(s);

    return "uploaded";
}

Also I know the file is getting to the service through fiddler/breaks and I've successfully uploaded and downloaded files by hard coding in a file like this:

using (var fileStream = System.IO.File.OpenRead(@"C:\file.zip"))
{
    blob.UploadFromStream(fileStream);
}

Edit: HTML

<form action='http://127.0.0.1:81/service.svc/Upload' method="post">
    <input type="file" name="file" id="btnUpload" value="Upload" />
    <input type="submit" value="Submit" class="btnExercise" id="btnSubmitExercise"/>
</form>
4

1 回答 1

4

您的代码看起来正确。但我对您收到的流媒体表示怀疑。你确定它包含数据?你能试试下面的代码吗?它返回上传 blob 后收到的总字节数。

using (var ms = new MemoryStream())
{
    byte[] buffer = new byte[32768]; 
    int bytesRead, totalBytesRead = 0; 

    do 
    { 
        bytesRead = stream.Read(buffer, 0, buffer.Length); 
        totalBytesRead += bytesRead; 

        ms.Write(buffer, 0, bytesRead); 
    } while (bytesRead > 0); 

    blob.UploadFromStream(ms);

    return String.Format("Uploaded {0}KB", totalBytesRead/1024);
}
于 2012-10-10T15:24:51.783 回答