我正在嘗試將影像上傳到 Azure 存盤容器。
使用 UploadBlobWithRestAPI,我試圖呼叫其余的 PUT API 并使用 AuthorizationHeader,我試圖為 API 呼叫創建授權。
我正在獲取在容器中創建的影像。但是,由于某種原因,影像不是可讀格式。從容器下載影像并嘗試在資源管理器中打開時,出現“我們似乎不支持這種檔案格式”。任何想法?
public void UploadBlobWithRestAPI(string MachineName,string ImageName)
{
string storageKey = "Storagekey";
string storageAccount = "Account";
string containerName = "test-container";
string blobName = "test2.jpg";
string method = "PUT";
Byte[] imageContentBytes = System.IO.File.ReadAllBytes(@"C:\\Test2.jpg");
int imageContentLength = (Encoding.UTF8.GetString(imageContentBytes)).Length;
string requestUri = $"https://{storageAccount}.blob.core.windows.net/{containerName}/{blobName}";
System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
string now = DateTime.UtcNow.ToString("R");
request.Method = method;
request.ContentType = "application/octet-stream";
request.ContentLength = imageContentLength;
request.Headers.Add("x-ms-version", "2015-12-11");
request.Headers.Add("x-ms-date", now);
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.Headers.Add("Authorization", AuthorizationHeader(method, now, request, storageAccount, storageKey, containerName, blobName));
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(imageContentBytes)), 0, imageContentLength);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
MessageBox.Show(resp.StatusCode.ToString());
}
}
public string AuthorizationHeader(string method, string now, HttpWebRequest request, string storageAccount, string storageKey, string containerName, string blobName)
{
string headerResource = $"x-ms-blob-type:BlockBlob\nx-ms-date:{now}\nx-ms-version:2015-12-11";
string urlResource = $"/{storageAccount}/{containerName}/{blobName}";
string stringToSign = $"{method}\n\n\n{request.ContentLength}\n\n{request.ContentType}\n\n\n\n\n\n\n{headerResource}\n{urlResource}";
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(storageKey));
string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
String AuthorizationHeader = String.Format("{0} {1}:{2}", "SharedKey", storageAccount, signature);
return AuthorizationHeader;
}
uj5u.com熱心網友回復:
我相信問題來了,因為您將影像(二進制內容)作為字串上傳,這會破壞資料。
請嘗試更改以下內容:
int imageContentLength = (Encoding.UTF8.GetString(imageContentBytes)).Length;
到
int imageContentLength = imageContentBytes.Length;
和
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(imageContentBytes)), 0, imageContentLength);
}
到
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(imageContentBytes, 0, imageContentLength);
}
另外,請為內容型別設定適當的值。考慮到您上傳的檔案是 JPEG 影像,請將內容型別設定為image/jpeg而不是application/octet-stream. 這將確保影像在瀏覽器中加載時正確顯示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448455.html
