简体   繁体   English

如何在ASP.NET MVC中上传带有其他数据的文件

[英]How to upload files with additional data in ASP.NET MVC

How can i upload a file with additional data in ASP.NET MVC? 如何在ASP.NET MVC中上传包含其他数据的文件? This is what I have so far: 这是我到目前为止的内容:

 @using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post))
 {
     @Html.TextBoxFor(a=>a.SiteNameKey)

     <input type="file" name="logo" id="logo" />
     <input type="submit" />
 }

Action: 行动:

[HttpPost]
public ActionResult CreateSiteLogo(SiteSettingsAPIModel siteSetting)
{
    // Handle model
}

Model: 模型:

public class SiteSettingsAPIModel
{
    public int Id { get; set; }
    public string SiteNameKey { get; set; }
    public byte[] SiteLogo { get; set; }
    public string ImageFormat { get; set; }
}

I can only get the value of the input[text] but not the input[file]. 我只能获取input [text]的值,而不能获取input [file]。 I tried using Request.Files[0] but I'm always getting null. 我尝试使用Request.Files[0]但是我总是得到null。

If you are using file upload in View then you must specify the enctype = "multipart/form-data" in BeginForm 如果要在View中使用文件上传,则必须在BeginForm中指定enctype =“ multipart / form-data”

    @using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(a => a.SiteNameKey)

    <input type="file" name="logo" id="logo" />
        <input type="submit" />
}

and in the Controller side, 在控制器端,

public ActionResult CreateSiteLogo(SiteSettingsAPIModel siteSetting, HttpPostedFileBase logo)
    {
        //Getting the file path
        string path = Server.MapPath(logo.FileName);

        //getting the file name
        string filename = System.IO.Path.GetFileName(logo.FileName);
        using (var binaryReader = new BinaryReader(logo.InputStream))
        {
            fileContent = binaryReader.ReadBytes(logo.ContentLength);
        }
        siteSetting.SiteLogo = fileContent;

        return View();
    }

the controller code shall be modified according to your requirement. 控制器代码应根据您的要求进行修改。 Hope its helpful 希望对您有所帮助

This could help: 这可以帮助:

@model SandBox.Web.Models.SiteSettingsAPIModel
@using (Html.BeginForm("CreateSiteLogo", "SiteSettings", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(a => a.SiteNameKey)

    <input type="file" name="SiteLogo" id="logo" />
    <input type="submit" />
}

public class SiteSettingsAPIModel
{
    public int Id { get; set; }
    public string SiteNameKey { get; set; }
    public HttpPostedFileBase SiteLogo { get; set; }
    public string ImageFormat { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM