如何下载MVC3文件? [英] How to download files in mvc3?

查看:142
本文介绍了如何下载MVC3文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个网站它需要能够上传和下载各种文件。如.PHP,.rar或JPG格式,的.cs,.PDF,.txt和等等。当我使用纯HTML这样的:

 < A HREF =@ Model.dList [I] .filePath>下载和LT; / A>

它显示在浏览器中的TXT和JPEG文件的内容,但我不希望这种情况发生。我猜我需要使用控制器,并写了一些片code的它。我做了一些研究,并计算出它是与文件的contentType属性。我跟他们打了一下,写了一个函数

控制器:

 公共FileResult DownloadDoc(INT DID)
    {
        字符串文件路径= getFilePath(DID);
        字符串的contentType =的getContentType(DID);
        文件路径= Path.Combine(使用Server.Mappath(dr.GetString(文件路径)),dr.GetString(文件名));
        返回文件(文件路径,则contentType);
    }

查看:

  @ Html.ActionLink(下载,DownloadDoc,新{DID = @ M​​odel.dList [I] .documentationID})

通过这个功能的文件下载,但它的名字是DownloadDoc始终,没有任何扩展名。我在这里卡住了。

我应该做任何花哨而我上传的文件?顺便说一下,后我上传的文件及其路径,CONTENTTYPES和文件名被存储在数据库中。我应该怎么办?


解决方案

 字符串文件名=FILENAME.TXT;
返回文件(文件路径,则contentType,文件名);

然后,文件名称将是变量的值文件名

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?

解决方案

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

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

这篇关于如何下载MVC3文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆