How to upload a file using MVC4 / Razor

I have an MVC application. And I want to download a pdf file.

This is part of my view:

<p>
    <span class="label">Information:</span>
    @using (Html.BeginForm("DownloadFile")) { <input type="submit" value="Download"/> }
</p>

And this is part of my controller:

   private string FDir_AppData = "~/App_Data/";

   public ActionResult DownloadFile()
    {
        var sDocument = Server.MapPath(FDir_AppData + "MyFile.pdf");

        if (!sDocument.StartsWith(FDir_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(sDocument))
        {
            return HttpNotFound();
        }

        return File(sDocument, "application/pdf", Server.UrlEncode(sDocument));
    }

How to download a specific file?

+4
source share
2 answers

Possible solution - specify the form method and controller name:

@using (Html.BeginForm("DownloadFile", "Controller", FormMethod.Get))
        { <input type="submit" value="Download" /> }

or try using an action link instead of a form:

@Html.ActionLink("Download", "DownloadFile", "Controller")

or try providing a direct url to the file:

<a href="~/App_Data/MyFile.pdf">Download</>

This is not a good practice due to security concerns, but you can try ... Alternatively, you can bind the file location to some helper method @Html:

public static class HtmlExtensions {
    private const string FDir_AppData = "~/App_Data/";

    public static MvcHtmlString File(this HtmlHelper helper, string name){
        return MvcHtmlString.Create(Path.Combine(FDir_AppData, name));
    }
}

And in the view:

<a href="@Html.File("MyFile.pdf")">Download</>
+9
source

DownloadFile :

 public ActionResult DownloadFile()

To:

 public FileResult DownloadFile()

, , UrlEncode , :

return File(sDocument, "application/pdf", sDocument);

, .

+6

All Articles