简体   繁体   English

如何将byte []转换为模型

[英]How convert byte[] into a model

I'm reading this answer to upload a file using MVC. 我正在阅读此答案以使用MVC上传文件。 I already have the file after a InputStream.Read but don't know how use it to create the IEnumerable<MyModel> so I can send it to db using EF. 我已经在InputStream.Read之后有了文件,但是不知道如何使用它创建IEnumerable<MyModel>所以我可以使用EF将其发送到db。 The file is a CSV file, I know the structure of. 该文件是CSV文件,我知道其结构。

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

[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");
}

My Model: 我的模特:

public class PriceViewModel
{        
    public int PriceId { get; set; }

    public int? YearSelected { get; set; }
    public int? WeekSelected { get; set; }
    public int? StateSelected { get; set; }
}

Convert the bytes to string 将字节转换为字符串

var csv = Encoding.UTF8.GetString(uploadedFile);

and then parse the CSV into the models. 然后将CSV解析为模型。

CsvHelper should help a lot with that. CsvHelper应该对此提供很多帮助。

var textReader = new StringReader(csv);
var helper = new CsvHelper(textReader);
IEnumerable<PriceViewModel> records = helper.GetRecords<PriceViewModel>();

From there you can validate the data and save to database. 从那里您可以验证数据并将其保存到数据库。

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

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