使用ASP MVC3进行文件下载时出错

时间:2011-08-04 07:29:15

标签: asp.net-mvc-3 download

此代码应该使用mvc3 controller

下载文件
public FilePathResult GetFileFromDisk(String file)
{
     String path = AppDomain.CurrentDomain.BaseDirectory + "AppData/";
     String contentType = "text/plain";
     return File(path+file, contentType, file);
}

查看部分:

@Html.ActionLink("Download", "GetFileFromDisk","Upload", new { file = "textfile" },null);

但是,当我点击链接时,我收到此错误

  

无法找到路径'D:\ Project \ FileUploadDownload \ FileUploadDownload \ AppData \ textfile'的一部分。

  [DirectoryNotFoundException:找不到路径'D:\ Project \ FileUploadDownload \ FileUploadDownload \ AppData \ textfile'的一部分。]

为什么foldername在文件路径中重复?请提供解决方案......

1 个答案:

答案 0 :(得分:4)

试试这样:

public ActionResult GetFileFromDisk(string file)
{
    var appData = Server.MapPath("~/App_Data");
    var path = Path.Combine(appData, file);
    path = Path.GetFullPath(path);
    if (!path.StartsWith(appData))
    {
        // Ensure that we are serving file only inside the App_Data folder
        // and block requests outside like "../web.config"
        throw new HttpException(403, "Forbidden");
    }

    if (!System.IO.File.Exists(path))
    {
        return HttpNotFound();
    }

    var contentType = "text/plain";
    return File(path, contentType, Path.GetFileName(path));
}