我試圖簡單地上傳一個圖像文件到Azure blob存儲和文件正在使它在那裏,但文件大小比它應該是更大,當我通過瀏覽器下載文件,它不會作爲圖像打開。如何正確編碼二進制數據通過REST API發送PUT調用
我手動上傳了同一個文件,通過Azure界面和文件工作,是22k,通過我的代碼上傳是29k,並不起作用。
注意:有一點需要注意的是,與此代碼一起使用的所有示例僅發送文本文件。也許Encoding.UTF8.GetBytes(requestBody);線正在做呢?
這是我base64編碼我的數據
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase
byte[] binData;
using (BinaryReader b = new BinaryReader(hpf.InputStream))
binData = b.ReadBytes(hpf.ContentLength);
var result = System.Convert.ToBase64String(binData);
new BlobHelper("STORENAMEHERE", "SECRETKEY").PutBlob("images", "test.jpg", result);
這是我使用的是把數據是什麼,它https://azurestoragesamples.codeplex.com/
public bool PutBlob(string container, string blob, string content)
{
return Retry<bool>(delegate()
{
HttpWebResponse response;
try
{
SortedList<string, string> headers = new SortedList<string, string>();
headers.Add("x-ms-blob-type", "BlockBlob");
response = CreateRESTRequest("PUT", container + "/" + blob, content, headers).GetResponse() as HttpWebResponse;
response.Close();
return true;
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError &&
ex.Response != null &&
(int)(ex.Response as HttpWebResponse).StatusCode == 409)
return false;
throw;
}
});
}
public HttpWebRequest CreateRESTRequest(string method, string resource, string requestBody = null, SortedList<string, string> headers = null,
string ifMatch = "", string md5 = "")
{
byte[] byteArray = null;
DateTime now = DateTime.UtcNow;
string uri = Endpoint + resource;
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = method;
request.ContentLength = 0;
request.Headers.Add("x-ms-date", now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
request.Headers.Add("x-ms-version", "2009-09-19");
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
request.Headers.Add(header.Key, header.Value);
}
if (!String.IsNullOrEmpty(requestBody))
{
request.Headers.Add("Accept-Charset", "UTF-8");
byteArray = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteArray.Length;
}
request.Headers.Add("Authorization", AuthorizationHeader(method, now, request, ifMatch, md5));
if (!String.IsNullOrEmpty(requestBody))
request.GetRequestStream().Write(byteArray, 0, byteArray.Length);
return request;
}
猜測它與大小無關,而是與請求中的標題相關。你可以添加調用'CreateRESTRequest()'的代碼嗎? – vorou
@vorou OP更新 – user3953989
從22k到29k的大小增加大約爲3:4,所以看起來你在某處是兩次Base64編碼。 – SBS