How to download files in mvc3?

2019-07-25 11:59发布

问题:

I'm programming a web site which needs to be capable of upload and download all kinds of files. Such as .php, .rar, .jpg, .cs, .pdf, .txt and so. When I use plain html like:

 <a href="@Model.dList[i].filePath">download</a>

it shows the content of the txt and jpeg files in the browser but I don't want this to happen. I'm guessing I need to use controller and write some piece of code for it. I did some research and figured out it has something to do with contentType attribute of files. I played with them a bit and wrote a function

Controller:

public FileResult DownloadDoc(int dID)
    {
        string filePath = getFilePath(dID);
        string contentType = getContentType(dID);
        filePath = Path.Combine(Server.MapPath(dr.GetString("FilePath")), dr.GetString("FileName"));
        return File(filePath, contentType);
    }

View:

    @Html.ActionLink("Download", "DownloadDoc", new { dID = @Model.dList[i].documentationID })

With this function a file is downloaded but it's name is DownloadDoc always and without any extension. I'm stuck here.

Should I do anything fancy while i'm uploading the files? By the way, after I upload the files their paths, contenttypes and file names are stored in database. What should I do?

回答1:

string fileName = "FileName.txt";
return File(filePath, contentType, fileName);

Then, the file name will be the value of variable fileName.



回答2:

Use the third parameter of the File() function:

return File(filePath, contentType, downloadFileName);