Google Drive api将文件名上传为“无标题”

时间:2014-01-16 08:22:55

标签: asp.net c#-4.0 google-drive-api google-apps

我可以从我的网站上传文件到谷歌驱动器,但我的问题是它会在上传后将文件显示为无标题。

如何在上传文件中添加或发布标题。

谢谢,

我的代码:

public string UploadFile(string accessToken, byte[] file_data, string mime_type)
    {
        try
        {
            string result = "";
            byte[] buffer = file_data;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");

            request.Method = "POST";

            request.ContentType = mime_type;
            request.ContentLength = buffer.Length;
            request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken);

            var stream = request.GetRequestStream();
            stream.Write(file_data, 0, file_data.Length);
            stream.Close();

            HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();//Get error here
            if(webResponse.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = webResponse.GetResponseStream();
                StreamReader responseStreamReader = new StreamReader(responseStream);
                result = responseStreamReader.ReadToEnd();//parse token from result

                var jLinq = JObject.Parse(result);

                JObject jObject = JObject.Parse(jLinq.ToString());

                webResponse.Close();

                return jObject["alternateLink"].ToString();
            }

            return string.Empty;


        }
        catch
        {
            return string.Empty;
        }
    }

3 个答案:

答案 0 :(得分:3)

我使用RestSharp将文件上传到Google云端硬盘。

    public static void UploadFile(string accessToken, string parentId)
    {
        var client = new RestClient { BaseUrl = new Uri("https://www.googleapis.com/") };

        var request = new RestRequest(string.Format("/upload/drive/v2/files?uploadType=multipart&access_token={0}", accessToken), Method.POST);

        var bytes = File.ReadAllBytes(@"D:\mypdf.pdf");

        var content = new { title = "mypdf.pdf", description = "mypdf.pdf", parents = new[] { new { id = parentId } }, mimeType = "application/pdf" };

        var data = JsonConvert.SerializeObject(content);

        request.AddFile("content", Encoding.UTF8.GetBytes(data), "content", "application/json; charset=utf-8");

        request.AddFile("mypdf.pdf", bytes, "mypdf.pdf", "application/pdf");

        var response = client.Execute(request);

        if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Unable to upload file to google drive");
    }

答案 1 :(得分:2)

使用google.apis dll完成它并不容易。您需要在发送文件的其余部分之前发送元数据。为此,您需要使用uploadType = multipart

https://developers.google.com/drive/manage-uploads#multipart

这应该让你开始抱歉它的代码墙。我没有时间为此创建一个教程。

FileInfo info = new FileInfo(pFilename);
//Createing the MetaData to send
List<string> _postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + info.Name + "\",");
_postData.Add("\"description\": \"Uploaded with SendToGoogleDrive\",");
_postData.Add("\"parents\": [{\"id\":\"" + pFolder + "\"}],");
_postData.Add("\"mimeType\": \"" + GetMimeType(pFilename).ToString() + "\"");
_postData.Add("}");
string postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);

// creating the Data For the file
byte[] FileByteArray = System.IO.File.ReadAllBytes(pFilename);

string boundry = "foo_bar_baz";
string url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + myAutentication.accessToken;

WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";

// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
                boundry,
                "application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
                boundry,
                GetMimeType(pFilename).ToString());

string footer = "\r\n--" + boundry + "--\r\n";

int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + FileByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson));   // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length);                                          // write the MetaData


 dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile));   // write the File ContentType
        dataStream.Write(FileByteArray, 0, FileByteArray.Length);                                  // write the file

        // Add the end of the request.  Start with a newline

        dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
        dataStream.Close();

        try
        {
            WebResponse response = request.GetResponse();
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            //Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
}
        catch (Exception ex)
        {
            return "Exception uploading file: uploading file." + ex.Message;

        }

如果您需要任何超出评论的说明,请告诉我。我勉强工作了一个月。它几乎与可恢复上传一样糟糕。

答案 2 :(得分:0)

我正在寻找给定问题的解决方案,之前我正在使用uploadType = resumable导致给定的问题,当我使用uploadType = multipart问题解决时...