0

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");
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Asad Saleem
  • 41
  • 1
  • 2
  • 9
  • You use MapPath and then don’t use that for actually returning a file, rather suddenly return a result to a folder. Create permissionSet and don’t use it for anything. – Sami Kuhmonen Oct 14 '17 at 04:05
  • Can you edit this code? – Asad Saleem Oct 14 '17 at 04:10
  • I Changed the code to this, But still not working var FileVirtualPath = ("~/Photos/" + fileName); return File(FileVirtualPath,"application/force-download", Path.GetFileName(FileVirtualPath)); – Asad Saleem Oct 14 '17 at 04:43

2 Answers2

2

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);
    }
etuncoz
  • 198
  • 3
  • 7
  • I changed the code to this, And now i am getting error ............. Exception Details: System.IO.FileNotFoundException: Could not find file 'D:\Work\Ment\Ment\Photos\photo.jpg'. – Asad Saleem Oct 14 '17 at 16:06
  • I tried adding this code in my controller in asp net core mvc project but cant figure out which import I need for Server – Steve W Apr 17 '18 at 09:24
  • @SteveW should be under System.Web, make sure you reference it in your project – etuncoz Apr 17 '18 at 09:38
  • I tried adding using System.Web but it doesn't work. I am trying to do this inside my MVC controller action method. Does this make a difference? I will make a new question and give you the link if you don't mind helping – Steve W Apr 17 '18 at 09:39
  • https://stackoverflow.com/questions/49874934/actionlink-and-method-to-download-file-from-asp-net-mvc-project – Steve W Apr 17 '18 at 09:51
  • sorry, didnt realize you were using .net core – etuncoz Apr 17 '18 at 10:10
1

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

Moien Tajik
  • 2,115
  • 2
  • 17
  • 39