如何将字节转换为文件asp.net MVC

时间:2019-02-21 04:58:25

标签: asp.net-mvc

我想下载我在数据库中上传的文件。该文件存储在字节数组中。我已经创建了getDataStudent函数,并且运行良好。 我的控制器在下面。

public class Student: Controller
{
      private StudentViewModel getDataStudent(StudentViewModel model)
      { 
        var students = db.students.ToList();
        var documents = documentRepo.GetList_Documents();

        var queryJoin1 = 
            from student in students
            from document in documents.Where(w => student .UniqueNumber == w.UniqueNumber).DefaultIfEmpty()
            select new StudentDto
            {
               ID = student.ID,
               Name = student.Name,
               File = document?.DetailFile ?? null, //file to download
            };
            IEnumerable <StudentDto> studentss= null;
            studentss = queryJoin1;

           return studentss;
       }

    public ActionResult Index(StudentViewModel model)
    { 
        studentViewModel = getDataStudent(model);
        return View(studentViewModel );
    }

    [HttpPost]
    public FileResult DownloadFile()
    {
       //code
    }

}

我的看法在下面

@model Student.Data.ViewModels.StudentViewModel
@using (Html.BeginForm())
{
  <table class="table">
            <tr>
                <th>Name</th>
                <th>File</th>             
            </tr>
             @foreach (Student.Data.ViewModels.StudentViewModel item in Model)
            {
              <tr>
                 <td>@Html.DisplayFor(modelitem => item.Name)</td>
                 <td> @Html.DisplayFor(modelitem => item.File)</td>    
              </tr>
            }
   </table>
}

文件结果仍然为空,我对使用文件结果感到困惑。 你们能告诉我如何使用我创建的getDataStudent函数在控制器上使用FileResult下载文件。 我以前从未做过文件下载功能。请帮助:)

1 个答案:

答案 0 :(得分:1)

您可以这样实现:

public FileStreamResult DownloadFile()
{
    // get your students here
    var students = ...
    string name = "yourname.txt";

    FileInfo info = new FileInfo(name);
    if (!info.Exists)
    {
        using (StreamWriter writer = info.CreateText())
        {
            foreach(var item in students){
               writer.WriteLine("{0} {1}", item.ID, item.Name);
            }

        }
    }

    return File(info.OpenRead(), "text/plain");

}