2012-10-10 84 views
4

我有一個簡單的應用程序,我正在做一個文件類型輸入到WCF服務的表單發佈。我試圖將表單文件上傳到Azure blob,然後通過點擊相應的blob url進行下載。上傳和下載流到Azure Blob

現在發生了什麼是我正在上傳文件到Azure,但是當我下載它時,文件不包含內容。例如,如果我上傳something.zip或something.gif,我可以從url下載它,但它們都不會包含任何內容。

我讀過,這可能是因爲流的位置未設置爲0.它不會讓我設置下面的流「流」的位置,所以我將它複製到一個memoryStream。可悲的是,這並沒有解決問題。

[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"; 
} 

而且我知道該文件越來越通過小提琴手/休息的服務,我已經成功地上傳和下載通過硬編碼的文件在文件中是這樣的:

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

編輯: 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> 
+0

」流的位置未設置爲0「。那解決了我的問題,謝謝+1 –

回答

3

您的代碼看起來正確。但我對你收到的信息流有懷疑。你確定它包含數據嗎?你可以嘗試下面的代碼嗎?它返回上傳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); 
} 
+0

你是對的「Uploaded 0KB」。我想我會添加我的客戶端代碼。 – user1134179

+0

所以真正的問題是爲什麼我的表單不能發送文件輸入中指定的文件? – user1134179