使用标题中的非ASCII字母将文件上传到Google云端硬盘

时间:2012-11-30 16:04:00

标签: c# google-drive-api

如果文件中包含非ASCII符号,如何将文件上传到Google云端硬盘 它的名字?

目前,我正在使用此方法开始上传到Google云端硬盘。但是,如果我传递的文件名包含非ASCII字母,则无法在JSON响应中返回ParseError。

    public string startUploadSession(string mimeType, long fileLength, string filename)
    {
        string uri = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable" + "&access_token=" + account.accessInfo.access_token;
        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";

        request.ContentType = "application/json; charset=utf-8";

        request.Headers.Add("X-Upload-Content-Type", mimeType);
        request.Headers.Add("X-Upload-Content-Length", fileLength.ToString());

        // Here we're providing file metadata
        File file = new File();
        file.title = filename;

        string requestBody = toJsonString(file);

        request.ContentLength = requestBody.Length;

        System.IO.Stream requestStream = request.GetRequestStream();

        requestStream.Write(requestBody.ToByteArray(), 0, requestBody.Length);

        requestStream.Close();

        try
        {
            var response = request.GetResponse();
            var reader = new System.IO.StreamReader(response.GetResponseStream());
            var responseBody = reader.ReadToEnd();

            return response.Headers["Location"];
        }
        catch (WebException ex)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(ex.Response.GetResponseStream());
            string error = reader.ReadToEnd();
            Logger.Error(error, "Getting upload uri");
            return null;
        }
    }

行。这是我的错。修复了部分代码:

System.IO.Stream requestStream = request.GetRequestStream();
byte[] utf8Bytes = requestBody.ToByteArray();

requestStream.Write(utf8Bytes, 0, utf8Bytes.Count());
requestStream.Close();

0 个答案:

没有答案