【问题标题】:.NET CSVReader Posting File.NET CSVReader 发布文件
【发布时间】:2018-06-29 16:58:44
【问题描述】:

我已经使用我可以在此处找到的最推荐的 nuget CSVReader 创建了一个 CSV 解析器。我认为我的代码几乎就在那里,它只是将文件发布到控制器操作方法,我找不到足够的东西。我得到了错误:

System.IO.FileNotFoundException: '找不到文件'C:\Program Files (x86)\IIS Express\System.Web.HttpPostedFileWrapper'。'

控制器动作方法:

    [HttpPost]
    public ActionResult CreateBulk(HttpPostedFileBase attachmentcsv)
    {
        if (ModelState.IsValid)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(attachmentcsv.ToString()), true))
            {
                csv.Configuration.HasHeaderRecord = true;
                var records = csv.GetRecords<Client>().ToList();

                foreach (var item in records)
                {
                    String Strip = item.homePage.Replace("https://www.", "").Replace("http://www.", "").Replace("https://", "").Replace("http://", "").Replace("www.", "");
                    string[] URLtests = { "https://www." + Strip, "http://www." + Strip, "https://" + Strip, "http://" + Strip };
                    string[] Metric = MajesticFunctions.MajesticChecker(URLtests);
                    var userId = User.Identity.GetUserId();
                    var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
                    var newclient = new Client { clientN = item.clientN, homePage = Metric[0], clientEmail = item.clientEmail, contName = item.contName.First().ToString().ToUpper() + item.contName.Substring(1), monthlyQuota = item.monthlyQuota, TrustFlow = Int32.Parse(Metric[1]), CitationFlow = Int32.Parse(Metric[2]), RI = Int32.Parse(Metric[3]), MJTopicsID = item.MJTopicsID, UserTableID = UserTableID };
                    ViewBag.newdomain = newclient;
                    db.Clients.Add(newclient);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
        }
        return RedirectToAction("Index");

查看上传按钮:

@using (Html.BeginForm("CreateBulk", "Clients", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<label for="attachment">Select a Csv File</label>
<label class="btn btn-default btn-file">
<input type="file" name="attachmentcsv" id="attachmentcsv" hidden>
</label>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
}

客户端模型:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Linkofy.Models
{
public class Client
{
    public int ID { get; set; }

    [Required]
    [Display(Name = "Client")]
    public string clientN { get; set; }

    [Display(Name = "Website")]
    public string homePage{ get; set; }

    [EmailAddress]
    [Display(Name = "Contact Email")]
    public string clientEmail { get; set; }

    [Display(Name = "Contact Name")]
    public string contName { get; set; }

    [Display(Name = "Monthly")]
    public int monthlyQuota { get; set; }

    [Display(Name = "TF")]
    public int TrustFlow { get; set; }

    [Display(Name = "CF")]
    public int CitationFlow { get; set; }

    [Display(Name = "RIPs")]
    public int RI { get; set; }

    public int? MJTopicsID { get; set; }
    public virtual MJTopics MJTopics { get; set; }

    public int UserTableID { get; set; }
    public virtual UserTable UserTable { get; set; }

    public virtual ICollection<Link> Links { get; set; }
    public virtual ICollection<Status> Statuss { get; set; }
}
}

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc


    【解决方案1】:

    您应该查看:File upload in MVC

    但是查看您的代码,我想指出一些事情:

    隔离attachmentcsv.ToString() 行,这似乎返回System.Web.HttpPostedFileWrapper 的类型,这就是为什么将这个字符串附加到文件位置的原因。

    我相信您可能正在寻找attachmentcsv.FileName,根据类型的文档(https://msdn.microsoft.com/en-us/library/system.web.httppostedfilewrapper(v=vs.110).aspx

    获取客户端上文件的完全限定名

    我不确定您使用的是框架版本还是 ASP 的核心版本,但我相信在 ASP 的框架版本中访问上传文件的“正确”方式(如链接答案中所示)是通过Request 对象: Request.Files.

    https://msdn.microsoft.com/en-us/library/system.web.httprequest.files(v=vs.110).aspx

    在 ASP 的核心版本中,您可以有一个 IFileForm,如下所示:

    https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

    [HttpPost("UploadFiles")]
    public async Task<IActionResult> Post(List<IFormFile> files)
    {
        long size = files.Sum(f => f.Length);
    
        // full path to file in temp location
        var filePath = Path.GetTempFileName();
    
        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }
    
        // process uploaded files
        // Don't rely on or trust the FileName property without validation.
    
        return Ok(new { count = files.Count, size, filePath});
    }
    

    希望对你有帮助

    【讨论】:

    • 哇,答案写得真好!谢谢你。因此,如果我创建一个 iformfile 的模型绑定,用额外的几行来模仿客户端模型,那么它会按照我想要的方式工作。通过 var records = csv.GetRecords().ToList(); iform 文件最初将其绑定到模型,以便我可以将其保存到数据库中?
    • 我也在使用 MVC5
    • 在 MVC5 中,这样的东西应该能够导入您的文件 (gist.github.com/joro550/544ba7b4a99b0285ac365328b786fff7)
    • 好像可以读取文件了!非常感谢,最后一个快速问题,它卡在 Id 列上,说它在文件中找不到,我如何让它忽略它?
    • 它说 ireader 配置不包含 willthrowonmissingfields 的定义,也许图书馆已经改变了,明天会更多地研究它,如果没有发布问题,谢谢你的时间!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2019-07-12
    • 2021-02-27
    • 1970-01-01
    • 2012-03-04
    相关资源
    最近更新 更多