ASP.Net MVC3 app从另一个网络服务器下载文件到客户端

时间:2012-09-12 16:34:30

标签: asp.net-mvc-3 download

我们目前使用以下代码将文件从网络服务器下载到旧的ASP.net页面中的客户端。

我们已经在MVC3中重写了应用程序,并希望升级此功能。我看过几篇声称可以通过在web.config中编写以下行来从网络共享访问该文件的帖子

<authentication mode="Windows"/>
<identity impersonate="true" userName="" password="" />

但是,我们目前正在使用Forms身份验证模式登录该站点。这会干扰登录功能吗?

这是我们的下载代码。

Partial Class DownloadFile2
   Inherits System.Web.UI.Page

   Private BufferSize As Integer = 32 * 1024

   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

      Dim path As String = Request.Params("File")
      path = "\\speedy\wanfiles\" + path.Substring(3)
      Dim file As System.IO.FileInfo = New System.IO.FileInfo(path)
      Dim Buffer(BufferSize) As Byte
      Dim SizeWritten, fileindex As Integer
      Response.Clear()

      Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name)
      Response.AddHeader("Content-Length", file.Length.ToString)

      Response.ContentType = "application/octet-type"
      Response.Flush()

      fileindex = 0
      Do
         // not sure about this GM.AlasData code below
         SizeWritten = GM.AlasData.ReadFileBlock(file.FullName, Buffer, fileindex, BufferSize) 
         Response.OutputStream.Write(Buffer, 0, SizeWritten)
         Response.Flush()
         If SizeWritten < BufferSize Then
            Exit Do
         Else
            fileindex = fileindex + SizeWritten
         End If
      Loop

      Response.End()


   End Sub

End Class

我发现此代码使用MVC3进行下载但无法访问该文件,因为它被视为本地文件。

public FileResult Download(string FilePath)
{
    if (FilePath != null)
    {
        string path = FilePath;
        string contentType;
        // files are stored on network server named speedy
        path = string.Concat(@"\\speedy\files\", HttpUtility.UrlDecode(path));
        System.IO.FileInfo file = new System.IO.FileInfo(path);
        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(file.Extension.ToLower());
        if (rk != null && rk.GetValue("Content Type") != null)
        {
            contentType = rk.GetValue("Content Type").ToString();
        }
        else
        {
            contentType = "application/octet-type";
        }

        //Parameters to file are
        //1. The File Path on the File Server
        //2. The content type MIME type
        //3. The parameter for the file save by the browser
        return File(file.FullName, contentType, file.Name);

    }
    else
    {
        return null;
    }
}

在我们可以执行此功能的地方需要做些什么来解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以删除身份验证模式= Windows行,因为您正在使用表单身份验证。使用模拟并确保帐户具有您尝试访问的网络位置的读取权限。应该工作。

答案 1 :(得分:0)