asp.net-mvc 使用 ASP.NET MVC 将文件上传到数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15106190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:37:14  来源:igfitidea点击:

Uploading Files into Database with ASP.NET MVC

asp.net-mvcasp.net-mvc-scaffolding

提问by Mangesh Kaslikar

I want to give a facility on my form for user to upload files and save in Database. How is this done in ASP.NET MVC.

我想在我的表单上为用户提供一个工具来上传文件并保存在数据库中。这是如何在 ASP.NET MVC 中完成的。

What DataType to write in my Model Class. I tried with Byte[], but during the scaffolding the solution could not generate the appropriate HTML for it in the corresponding View.

在我的模型类中写入什么数据类型。我尝试过Byte[],但是在搭建脚手架期间,解决方案无法在相应的视图中为其生成适当的 HTML。

How are these cases handled?

这些案件如何处理?

回答by Darin Dimitrov

You could use a byte[]on your model and a HttpPostedFileBaseon your view model. For example:

您可以byte[]在模型上使用 a ,HttpPostedFileBase在视图模型上使用 a 。例如:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

and then:

进而:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        byte[] uploadedFile = new byte[model.File.InputStream.Length];
        model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

        // now you could pass the byte array to your model and store wherever 
        // you intended to store it

        return Content("Thanks for uploading the file");
    }
}

and finally in your view:

最后在你看来:

@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
        @Html.ValidationMessageFor(x => x.File)
    </div>

    <button type="submit">Upload</button>
}