Search code examples
asp.netasp.net-mvc-3downloadimagedownload

how to make a picture file downloadable?


I have an ASP.NET MVC3 application and I want to link_to an image file (png, jpeg, gif, etc), and when user clicks on it, the file goes to download, instead of the browser shows it; is there any way to do this?


Solution

  • take your link something like this:

    @Html.ActionLink(
        "Download Image", // text to show
        "Download", // action name
        ["DownloadManager", // if need, controller]
        new { filename = "my-image", fileext = "jpeg" } // file-name and extension 
    )
    

    and action-method is here:

    public FilePathResult Download(string filename, string fileext) {
        var basePath = Server.MapPath("~/Contents/Images/");
        var fullPath = System.IO.Path.Combine(
            basePath, string.Concat(filename.Trim(), '.', fileext.Trim()));
        var contentType = GetContentType(fileext);
        // The file name to use in the file-download dialog box that is displayed in the browser.
        var downloadName = "one-name-for-client-file." + fileext;
        return File(fullPath, contentType, downloadName);
    }
    
    private string GetContentType(string fileext) {
        switch (fileext) {
            case "jpg":
            case "jpe":
            case "jpeg": return "image/jpeg";
            case "png": return "image/x-png";
            case "gif": return "image/gif";
            default: throw new NotSupportedException();
        }
    }
    

    UPDATE: in fact, when a file is sending to a browser, this key/value will be generated in http-header:

    Content-Disposition: attachment; filename=file-client-name.ext
    

    which file-client-name.ext is the name.extension that you want the file save-as it on client system; for example, if you want to do this in ASP.NET (none mvc), you can create a HttpHandler, write the file-stream to Response, and just add the above key/value to the http-header:

    Response.Headers.Add("Content-Disposition", "attachment; filename=" + "file-client-name.ext");
    

    just this, enjoy :D