2016-12-07 50 views
0

如何使用ASP.NET MVC中的其他数据上传文件? 这是我到目前为止有:如何使用ASP.NET MVC中的其他数据上载文件

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

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

操作:

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

型号:

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

我只能得到输入[文]的值而不是输入[文件]。我尝试使用Request.Files[0],但我总是变空。

+0

显示的代码。 – Mairaj

+0

您是否在您的'ActionResult'上放置了一个断点以查看文件是否正在通过? – Izzy

+0

更好的方法是将一个onchange侦听器添加到文件输入中,通过ajax发布文件,并返回文件名作为保存的文件名。然后你可以添加文件名到模型 –

回答

1

这可以帮助:模型

@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; } 
} 
3

如果您使用的是查看文件上传,那么你必须在BeginForm

@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" /> 
} 

,并在控制器端指定ENCTYPE = “的multipart/form-data的”,

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(); 
    } 

控制器代码应根据您的要求进行修改。希望它有用

+0

非常感谢:) 但事实证明,我需要将徽标的类型从字节数组更改为http张贴文件库。这样我就不必为我的动作添加第二个参数。 再次感谢:D – user3159792

相关问题