.NET CSVReader发布文件

时间:2018-01-20 16:12:18

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

我使用我在这里找到的最推荐的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; }
}
}

1 个答案:

答案 0 :(得分: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});
}

希望这有帮助