我正在使用 google drive API 和示例 DrEdit 项目,我想将挑选的 pdf 文件保存到本地目录中。我目前的步骤
我正在使用 DownloadFile 方法获取文件内容流
public static string DownloadFile(IAuthenticator auth, String downloadUrl) { string result = ""; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(downloadUrl)); auth.ApplyAuthenticationToRequest(request); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); return reader.ReadToEnd(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return result; }
然后我将其转换为 byte[] 并尝试保存:
public static string SaveFileToTmpDir(byte[] fileBytes, string fileName) { fileName = Path.Combine(Environment.GetEnvironmentVariable("temp"), fileName); using (FileStream fs = File.Create(fileName, fileBytes.Length, FileOptions.Asynchronous)) { fs.Write(fileBytes, 0, fileBytes.Length); } return fileName; }
这是我的操作->我正在从视图中调用该操作->将文件保存在 tmp 目录中并返回保存文件的路径:
[HttpPost] public JsonResult loadFile(string id) { IAuthenticator authenticator = Session["authenticator"] as IAuthenticator; DriveService service = Session["service"] as DriveService; if (authenticator == null || service == null) { Response.Redirect(Utils.GetAuthorizationUrl("", "")); } Google.Apis.Drive.v2.Data.File file = service.Files.Get(id).Fetch(); string fileStream = Utils.DownloadFile(authenticator, file.DownloadUrl); string filePath = Utils.SaveFileToTmpDir(StrToByteArray(fileStream), file.Title); return Json(new { filePath = filePath }); }
但在这样做之后,我得到 pfd 文件完全空白。有什么想法可以得到准确的副本吗?