将ASP.NET Drive文件从ASP.NET下载到用户的浏览器默认对话框

时间:2016-08-27 14:56:12

标签: asp.net asp.net-mvc google-drive-realtime-api

我正在尝试使用ASP.NET,MVC,Google Drive API V2将Google云端硬盘文件下载到用户的默认下载文件夹,通过服务帐户进行身份验证。

我见过的示例使用_saveTo路径和文件名。我不希望用户在开始下载之前必须指定此信息。我只是希望用户点击Web应用程序中的文件并让它显示浏览器下载对话框。这可能吗?

以下是3层:

CSHTML

<td>
    <a href="@Url.Action("DownloadFile", "GoogleDrive", new { _fileId = item.DriveId })">@Html.DisplayFor(x => item.FileName)</a>
</td>

CONTROLLER

[HttpGet]
public ActionResult DownloadFile(string _fileId)
{
    GoogleDrivePageVM vm = new GoogleDrivePageVM();

    // Get Service
    DriveService _service = GoogleDrive.GoogleDriveAPI.GoogleDriveAuthentication();

    // Download File
    File _file = GoogleDrive.GoogleDriveAPI.GetFile(_service, _fileId);

    bool _success = GoogleDrive.GoogleDriveAPI.DownloadFile(_service, _file, null);     // _saveTo);  

    return RedirectToAction("GoogleDriveList", "GoogleDrive");
}

服务层

public static Boolean DownloadFile(DriveService _service, File _file, string _saveTo)
{
    if (!String.IsNullOrEmpty(_file.DownloadUrl))
    {
    try
    {
        var x = _service.HttpClient.GetByteArrayAsync(_file.DownloadUrl);
        byte[] arrBytes = x.Result;
        System.IO.File.WriteAllBytes("c://myFirstDownload.txt", arrBytes);    //_saveTo
        return true;
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred: " + e.Message);
        return false;
    }
    }
    else
    {
    // The file doesn't have any content stored on Drive.
    return false;
    }
}

我觉得我正在尝试实施错误的方法。有人可以澄清这是否可能,并指出我正确的方向。我可以从网页上使用文件的downloadURL吗?

1 个答案:

答案 0 :(得分:2)

您正在寻找的下载网址在Drive API中被称为webContentlink,它是使用files.get生成的。

  

webContentLink 用于在浏览器中下载文件内容的链接。这仅适用于包含二进制内容的文件   驱动。

此链接允许您直接从浏览器下载文件。

立即使用Try-it进行测试。