如何使用C#在ASP.NET MVC中下载文件?

时间:2017-10-14 03:51:00

标签: c# asp.net-mvc controller

我正在完成一项任务,而且我一直在下载部分。我可以上传文件。但是当我在上传后尝试下载相同的文件时,我收到一个错误(“访问被拒绝”)。

这是我写的代码:

[HttpGet]
public FileResult Download (string fileName)
{
    var permissionSet = new PermissionSet(PermissionState.None);

    var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, @"D:\Assignment\Ment\Ment\Photos");
    permissionSet.AddPermission(writePermission);

    var FileVirtualPath = Server.MapPath("~/Photos/" + fileName); //"~/Photos/" + fileName;

    return new FilePathResult(@"D:\Assignment\Ment\Ment\Photos", "application/octet-stream");
}

2 个答案:

答案 0 :(得分:1)

尝试类似的东西:

public FileResult Download(string ImageName)
{
    return File(“<your path>” + ImageName, System.Net.Mime.MediaTypeNames.Application.Octet);
}

另外,请访问此链接:

ASP.NET MVC Uploading and Downloading Files

Upload and download files using ASP.NET MVC

答案 1 :(得分:0)

你可以做到

[HttpGet]
    public virtual ActionResult Download(string fileName)
    {
        //fileName should be like "photo.jpg"
        string fullPath = Path.Combine(Server.MapPath("~/Photos"),fileName);
        return File(fullPath, "application/octet-stream", fileName);
    }