我正在玩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;
}
这是我的行动 - >我正在从视图到该动作进行ajax调用 - >将文件保存在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文件完全空白。有任何想法获得精确的副本?