![](/img/trans.png)
[英]Processing binary data in Web API from a POST or PUT REST request
[英]How to properly encode binary data to send over REST api PUT call
我試圖將圖像文件簡單地上傳到Azure blob存儲,並且該文件正在其中,但是文件大小大於應有的大小,並且當我通過瀏覽器下載文件時,它不會作為圖像打開。
我通過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;
}
我相信問題在於如何將二進制數據轉換為字符串,然后再將其轉換回字節數組。
在將二進制數據轉換為字符串時,您正在使用System.Convert.ToBase64String
但是從字符串中獲取字節數組時,您正在使用Encoding.UTF8.GetBytes
。 這很可能是造成不匹配的原因。
請更改以下代碼行:
byteArray = Encoding.UTF8.GetBytes(requestBody);
至
byteArray = System.Convert.FromBase64String(requestBody);
這應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.