简体   繁体   English

如何正确编码二进制数据以通过REST api PUT调用发送

[英]How to properly encode binary data to send over REST api PUT call

I'm trying to simply upload an image file to Azure blob store and the file is making it there but the file size is bigger than it should be and when I download the file via the browser it won't open as an image. 我试图将图像文件简单地上传到Azure blob存储,并且该文件正在其中,但是文件大小大于应有的大小,并且当我通过浏览器下载文件时,它不会作为图像打开。

I manually uploaded the same file via the Azure interface and the file works and is 22k, uploading via my code is 29k and doesn't work. 我通过Azure界面手动上传了相同的文件,该文件可以正常工作,大小为22k,通过我的代码上传的情况下,文件大小为29k,不起作用。

NOTE: One thing to note is that all the examples used with this code only send text files. 注意:要注意的一件事是,此代码使用的所有示例仅发送文本文件。 Maybe the Encoding.UTF8.GetBytes(requestBody); 也许是Encoding.UTF8.GetBytes(requestBody); line is doing it? 线在干吗?

This is where I'm Base64 encoding my data 这是我在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);

This is what I'm using to PUT the data, it's from https://azurestoragesamples.codeplex.com/ 这就是我用来放置数据的方法,它来自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;
}

I believe the problem is with how you're converting the binary data to string and then converting it back to byte array. 我相信问题在于如何将二进制数据转换为字符串,然后再将其转换回字节数组。

While converting binary data to string, you're using System.Convert.ToBase64String however while getting the byte array from string you're using Encoding.UTF8.GetBytes . 在将二进制数据转换为字符串时,您正在使用System.Convert.ToBase64String但是从字符串中获取字节数组时,您正在使用Encoding.UTF8.GetBytes Most likely this is causing the mismatch. 这很可能是造成不匹配的原因。

Please change the following line of code: 请更改以下代码行:

byteArray = Encoding.UTF8.GetBytes(requestBody);

to

byteArray = System.Convert.FromBase64String(requestBody);

and that should fix the problem. 这应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM