如何使用FileResult从数据库下载文件

时间:2017-11-07 07:48:03

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我想制作视频下载,但我总是收到错误,有人可以解决这个问题吗

这是我的RazorView

<table>
    <tr>
        <th>Upload</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.ActionLink("Download", "download", "Home")</td>
        </tr>
    }
</table>

这是我的控制器

    public FileResult download(string fileName)
    {
        return File("~/App_Data/uploads", "multipart/form-data", fileName);
    }

在我的视图中单击下载后,我总是收到错误,有人可以修复我的代码..

这是我的上传控制器

    [HttpPost]
    public ActionResult Index(updown viewModel, HttpPostedFileBase model)
    {
        // extract only the filename
        var fileName = Path.GetFileName(Request.Files[0].FileName);

        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

        try
        {
            if (System.IO.File.Exists(path))
            {
                ModelState.AddModelError("uploadError", "Duplicate Data");
            }
            else
            {
                Request.Files[0].SaveAs(path);
            }

        }
        catch (Exception)
        {
            ModelState.AddModelError("uploadError", "Can't save file to disk");
        }

        if (ModelState.IsValid)
        {
            // put your logic here
            updown item = new updown();
            item.upload = fileName;
            db.updowns.Add(item);
            db.SaveChanges();

            return RedirectToAction("Index", "Home");

        }

        return View(viewModel);
    }

1 个答案:

答案 0 :(得分:0)

这当然不是使用FilePathResult的好方法:

return File("~/App_Data/uploads", "multipart/form-data", fileName);

下载文件的正确FilePathResult构造函数应如下所示:

public FilePathResult(string fileName, string contentType, string fileDownloadName)

你可以做些什么来修复它是检索文件位置的正确路径,然后设置适当的内容类型(即MIME类型)&amp;像这样返回FilePathResult

public FileResult Download(string fileName)
{
    // other stuff

    // read all contents from source file
    string path = Path.Combine(Server.MapPath("~/App_Data/uploads/"), fileName);

    // set content type, e.g. 'application/pdf' for PDF files
    // or use 'System.Net.Mime.MediaTypeNames' to get predefined content types
    string contentType = MimeMapping.GetMimeMapping(path);

    // return FilePathResult to download
    return File(path, contentType, fileName);
}

然后,使用ActionLink参数将fileName设置为您的控制器操作,如下所示:

@Html.ActionLink("Download", "Download", "Home", new { fileName = Model.FileName }, null)

注意:Model.FileName是一个viewmodel属性,您可以根据viewmodel配置从上传的文件中分配文件名。

类似问题:

Download File from FileSystem no matter the file type in MVC