1

如果文件标题中包含非 ASCII 符号,我如何将文件上传到 Google Drive?

目前我正在使用这种方法开始上传到 Google Drive。但是,如果我传递的文件名包含非 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();
4

0 回答 0