从MVC中的httppostdfilebase获取值

本文关键字:获取 httppostdfilebase 中的 MVC | 更新日期: 2023-09-27 17:54:41

我的控制器:

    [HttpPost]
    public ActionResult ShowExcelFile(HttpPostedFileBase getFile)
    {
        //Make something with values of getFile
        return PartialView("ShowExcelFile");
    }

在我看来:

@using (Html.BeginForm("ShowExcelFile", "ShowExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <input type="file" id="getFile" name="getFile" /><br />
     <input type="submit" value="Upload file" />
}

我如何从getFile读取值?

从MVC中的httppostdfilebase获取值

解析Excel文件的一个简单方法是使用一个库,如Excel Data Reader(也可以作为Nuget包提供)。安装后,读取Excel文件非常简单。

using Excel;
[HttpPost]
public ActionResult ShowExcelFile(HttpPostedFileBase getFile)
{
    if (getFile != null && getFile.ContentLength > 0)
    {
        // .xlsx
        IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(getFile.InputStream);
        // .xls
        IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(getFile.InputStream);
        reader.IsFirstRowAsColumnNames = true; // if your first row contains column names
    }
    return PartialView("ShowExcelFile");
}

从这一点来看,如果不知道Excel文件的内容,就很难说出你的确切需求。您可以将文件转换为System.Data.DataSet,它将包含Excel文件的每个工作表和数据。

DataSet dataSet = reader.AsDataSet();

您可以通过将ViewModel添加为属性来完成此操作:

<<p> 视图/strong>
@using (Html.BeginForm("ShowExcelFile", "ShowExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     @Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br />
     <input type="submit" value="Upload file" />
}

public class AModel 
{
    public AModel()
    {
        Files = new List<HttpPostedFileBase>();
    }
    public List<HttpPostedFileBase> Files { get; set; }
    // Rest of model details
}

您可以通过删除不需要的参数来检索文件,例如

控制器

[HttpPost]
public ActionResult ShowExcelFile(AModel model) 
 {
    var file = model.Files[0];
    ...
 }

我不知道你这是什么意思

用getFile

使用

获取文件扩展名
string fileExtension = Path.GetExtension(getFile.FileName);
//save this file using

string path = Path.Combine(Server.MapPath(Url.Content("~/Content")), "Name"+fileExtension);
file.SaveAs(path);