3

I already go a connection with the OAuth 2.0 protocol. I am using REST and C# to get file- and folder information, create folders etc. through WinForms.

Im not able to upload a picture. (A text file I can upload but when I try to upload a picture I can't open it in OneDrive for Business) This is what I got now:

public void CreateFile(string folderPath, string fileName, bool overwrite, byte[] data)
{
    string strData = System.Text.Encoding.UTF8.GetString(data);
    string parameters = strData;

    string strOverwrite = overwrite.ToString().ToLower();
    string response = HttpPostWithAccessToken(this.ServiceUri + "/web/GetFolderByServerRelativeUrl('" + folderPath + "')/Files/Add(url='" + fileName + "', overwrite=" + strOverwrite + ")", parameters);
}

The method to upload the data:

private string HttpPostWithAccessToken(string uri, string parameters)
{
    // Set settings
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
    request.ContentLength = bytes.Length;

    request.ContentType = "application/json;odata=verbose";
    request.Method = "POST";
    request.Accept = "application/json";
    request.Headers.Add("client-request-id", Guid.NewGuid().ToString());
    request.Headers.Add("Authorization", "Bearer " + AccessToken);

    // Set the parameters
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
    {
        writer.Write(parameters);
    }

    // Get the response
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        return reader.ReadToEnd();
    }
}

How to get this working with images as well?

  • this.ServiceUri contains "_api/" ? – b1c10 Jan 16 '15 at 18:03
  • try remove encoding, because you are working with image and not text. – b1c10 Jan 16 '15 at 18:15
  • and other, when object is a image or vudeo use BinaryWriter. – b1c10 Jan 16 '15 at 18:35
2

Better later then never, apparently you should not convert byte array into string via Encoding:

string strData = System.Text.Encoding.UTF8.GetString(data);

and then convert it back:

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);

In fact that's the reason why uploaded picture is getting corrupted. See Jon Skeet answer:

You should absolutely not use an Encoding to convert arbitrary binary data to text. Encoding is for when you've got binary data which genuinely is encoded text - this isn't.

But in your case there is no need to convert byte array, instead use Stream.Write Method to write byte array into stream:

using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(data, 0, data.Length);
}

Modified example

    public static void CreateFile(string serviceUrl, string accessToken, string folderUrl, string fileName, bool overwrite, byte[] data)
    {
        var sOverwrite = overwrite.ToString().ToLower();
        var formDigestVal = RequestFormDigest(serviceUrl); //FormDigestValue is required for POST method
        HttpPostWithAccessToken(serviceUrl + "/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files/Add(url='" + fileName + "', overwrite=" + sOverwrite + ")", accessToken, formDigestVal,  data);
    }


    private static string HttpPostWithAccessToken(string url,string accessToken, string formDigestValue, byte[] data)
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "application/json;odata=verbose";
        request.Accept = "application/json;odata=verbose";
        request.Method = "POST";
        request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        request.Headers.Add("Authorization", "Bearer " + accessToken);
        request.Headers.Add("X-RequestDigest",formDigestValue);

        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
        }
        using (var response = request.GetResponse())
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.