我正在尝试简单地将图像文件上传到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;
}
答案 0 :(得分:2)
我认为问题在于您如何将二进制数据转换为字符串,然后将其转换回字节数组。
在将二进制数据转换为字符串时,您正在使用System.Convert.ToBase64String
,但在从字符串获取字节数组时,您使用的是Encoding.UTF8.GetBytes
。这很可能导致了不匹配。
请更改以下代码行:
byteArray = Encoding.UTF8.GetBytes(requestBody);
到
byteArray = System.Convert.FromBase64String(requestBody);
这应该解决问题。