Asad Saleem
Asad Saleem

Reputation: 41

How to download a file in ASP.NET MVC using C#?

I'm working on an assignment, and I'm stuck in downloading section. I can upload the file. But when I'm trying to download the same file after uploading, I get an error ("Access is denied").

Here is the code which I have written:

[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");
}

Upvotes: 0

Views: 12871

Answers (2)

Moien Tajik
Moien Tajik

Reputation: 2321

Try something like that :

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

Also, visit this links :

ASP.NET MVC Uploading and Downloading Files

Upload and download files using ASP.NET MVC

Upvotes: 2

etuncoz
etuncoz

Reputation: 198

You could do

[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);
    }

Upvotes: 2

Related Questions