How to download files in mvc3?

旧城冷巷雨未停 提交于 2019-12-11 10:59:52

问题


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


来源:https://stackoverflow.com/questions/11931708/how-to-download-files-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!