对于c#–在文件上传时使用CSVHelper感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解c#multipartfile上传文件,并且为您提供关于.netCsvHelper2.0、ASP.
对于c# – 在文件上传时使用CSVHelper感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解c# multipartfile上传文件,并且为您提供关于.net CsvHelper 2.0、ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件、asp.net-mvc – 使用CSVHelper将流输出到浏览器、asp.net-mvc-3 – 使用csvhelper(nuGET)和C#MVC导入CSV文件的宝贵知识。
本文目录一览:- c# – 在文件上传时使用CSVHelper(c# multipartfile上传文件)
- .net CsvHelper 2.0
- ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件
- asp.net-mvc – 使用CSVHelper将流输出到浏览器
- asp.net-mvc-3 – 使用csvhelper(nuGET)和C#MVC导入CSV文件
c# – 在文件上传时使用CSVHelper(c# multipartfile上传文件)
public class SurveyEmailListModelsModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { var csv = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var file = ((csv.RawValue as HttpPostedFileBase[]) ?? Enumerable.Empty<HttpPostedFileBase>()).FirstOrDefault(); if (file == null || file.ContentLength < 1) { bindingContext.ModelState.AddModelError( "","Please select a valid CSV file" ); return null; } using (var reader = new StreamReader(file.InputStream)) using (var csvReader = new CsvReader(reader)) { return csvReader.GetRecords<SurveyEmailListModels>().ToArray(); } } }
这些是我要映射到的对象:
public class SurveyEmailListModels { [Key] [CsvField(Ignore = true)] public int SurveyEmailListId { get; set; } [CsvField(Index = 0)] public int ProgramId { get; set; } [CsvField(Index = 1)] public virtual SurveyProgramModels SurveyProgramModels { get; set; } [CsvField(Index = 2)] public string SurveyEmailAddress { get; set; } [CsvField(Index = 3)] public bool SurveyResponded { get; set; } }
在Visual Studio调试器中,我收到一个错误:
> base {“在访问数据之前必须先在读取器上调用read”.)CsvHelper.CsvHelperException {CsvHelper.CsvReaderException}
解决方法
using (var reader = new StreamReader(file.InputStream)) using (var csvReader = new CsvReader(reader)) { csvReader.Read(); return csvReader.GetRecords<SurveyEmailListModels>().ToArray(); }
.net CsvHelper 2.0
http://joshclose.github.io/CsvHelper/ var outputmatchPath = System.Configuration.ConfigurationManager.AppSettings[//FilePath]; TextReader requiredMatchElementsfileReader = File.OpenText(outputmatchPath); var matchCsv = new CsvReader(requir
http://joshclose.github.io/CsvHelper/
var outputmatchpath = system.configuration.configurationmanager.appsettings["//filepath"];
TextReader requiredMatchElementsfileReader = File.OpenText(outputmatchPath);var matchCsv = new CsvReader(requiredMatchElementsfileReader);
matchCsv.Configuration.RegisterClassMapRequiredMatchElementsMap>();
var requiredMatchList = matchCsv.GetRecordsRequiredMatchElements>().ToList();
public class RequiredMatchElements
{
public int IngredientId { set; get; }
public string IngredientName { set; get; }
public string RequriedElementsString { set; get; }
}
public class RequiredMatchElementsMap : CsvClassMap
{
public override void CreateMap()
{
Map(m => m.IngredientId).Name("IngredientId");
Map(m => m.IngredientName).Name("IngredientName");
Map(m => m.RequriedElementsString).Name("RequriedElementsString");
}
}
Write
using (TextWriter streamWriter =
new StreamWriter(HttpContext.Current.Server.MapPath("/App_Data/Top5000Instagram.csv")))
{
var csv = new CsvWriter(streamWriter);
csv.WriteRecords(dateList);
}
ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件
ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件
目录导航:
前言:
一、简单概述el-upload文件上传组件:
el-upload组件详情,查看官方解释:
常用的基本属性:
二、需要实现的效果:
三、代码实现:
前端Vue代码实现:
注意,清空已上传的文件列表:
Template代码:
Js中代码:
服务端ASP.NET Core WEB API来进行文件流数据接收和保存:
ASP.NET Core单文件和多文件上传并保存到服务端详情概述:
文章正文:
回到顶部
前言:
从开始学习Vue到使用element-ui-admin已经有将近快两年的时间了,在之前的开发中使用element-ui上传组件el-upload都是直接使用文件选取后立即选择上传,今天刚好做了一个和之前类似的文件选择上传的需求,不过这次是需要手动点击按钮把文件上传到服务器中进行数据导入,而且最多只能够选择一个文件进行上传,上传成功后需要对file-list中的文件列表数据进行清空操作,在这里服务端使用的是ASP.NET Core WEB API来进行文件流数据接收和保存。
回到顶部
一、简单概述el-upload文件上传组件:
el-upload组件详情,查看官方解释:
https://element.eleme.cn/#/zh-CN/component/upload
常用的基本属性:
参数 说明 类型 可选值 默认值
action 必选参数,上传的地址 string — —
headers 设置上传的请求头部 object — —
multiple 是否支持多选文件 boolean — —
data 上传时附带的额外参数 object — —
name 上传的文件字段名 string — file
with-credentials 支持发送 cookie 凭证信息 boolean — false
show-file-list 是否显示已上传文件列表 boolean — true
drag 是否启用拖拽上传 boolean — false
accept 接受上传的文件类型(thumbnail-mode 模式下此参数无效) string — —
on-preview 点击文件列表中已上传的文件时的钩子 function(file) — —
on-remove 文件列表移除文件时的钩子 function(file, fileList) — —
on-success 文件上传成功时的钩子 function(response, file, fileList) — —
on-error 文件上传失败时的钩子 function(err, file, fileList) — —
on-progress 文件上传时的钩子 function(event, file, fileList) — —
on-change 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 function(file, fileList) — —
before-upload 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 function(file) — —
before-remove 删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。 function(file, fileList) — —
list-type 文件列表的类型 string text/picture/picture-card text
auto-upload 是否在选取文件后立即进行上传 boolean — true
file-list 上传的文件列表, 例如: [{name: ''food.jpg'', url: ''https://xxx.cdn.com/xxx.jpg''}] array — []
http-request 覆盖默认的上传行为,可以自定义上传的实现 function — —
disabled 是否禁用 boolean — false
limit 最大允许上传个数 number — —
回到顶部
二、需要实现的效果:
通过单击文件上传按钮,能够弹窗一个Dialog文件选择框,通过点击选取文件按钮选择需要导入的Excel文件,然后手动点击数据导入按钮将Excel文件流通过Post请求传输到ASP.NET Core后台服务中,并进行数据保存操作。
弹出框效果如下图所示:
回到顶部
三、代码实现:
前端Vue代码实现:
注意,清空已上传的文件列表:
需要ref="upload"和file-list="fileList"这两个属性同时存在,否则即使调用this.$refs.upload.clearFiles();该方法也无效
Template代码:
<el-dialog title="数据导入" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
<el-uploadref="upload"
:action="actionRequestUrl"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="fileUploadSuccess"
:on-error="fileUploadFail"
:on-change="fileChange"
:file-list="fileList"
:limit="1"
:auto-upload="false"
:headers="headers">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button size="small" @click="downloadTemplate">导入模板下载</el-button>
<div slot="tip">请按照导入模板中的数据格式导入</div>
</el-upload>
<span slot="footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
<el-buttontype="success" @click="submitUpload">数据导入</el-button>
<!-- <div slot="tip">只能上传jpg/png文件,且不超过500kb</div> -->
</span>
</el-dialog>
Js中代码:
return {
fileList: [], //文件列表
dialogVisible: false,//Dialog显示状态
headers: { "X-Token": jwtToken }//设置上传的请求头部
fileDownloadUrl:''www.xxxx.com'',//文件下载地址
actionRequestUrl:''www.xxxx.com/fileUpload''//请求服务器接口地址
}},
//执行相关的方法
methods: {
//打开导入弹窗
openImporDialog() {
this.dialogVisible = true;
},
//关闭弹窗
handleClose() {
this.dialogVisible = false;
},
//上传到服务器
submitUpload() {
console.log(this.fileList);
if (this.fileList.length <= 0) {
this.$message.error("请先选择需要上传的文件!");
return false;
}
this.$refs.upload.submit();
},
//文件上传服务端失败时的钩子
fileUploadFail: function(err, file, fileList) {
console.log("文件上传失败", file, fileList);
},
//文件上传服务端成功时的钩子
fileUploadSuccess: function(response, file, fileList) {
console.log("上传成功");
console.log(response);
//清空已上传的文件列表
this.$refs.upload.clearFiles();
if (response.result) {
this.dialogVisible = false;
this.$message({
message: response.message,
type: "success"
});
} else {
this.$message.error(response.message);
}
},
//文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
fileChange(file, fileList) {
//解决无法判断el-upload是否上传过文件问题
this.fileList = fileList;
console.log("选择文件上传成功后显示的内容》", file, fileList);
},
//文件列表移除文件时的钩子
handleRemove(file, fileList) {
this.fileList = [];
// return this.$confirm(`确定移除 ${file.name}?`);
},
//点击文件列表中已上传的文件时的钩子
handlePreview(file) {
console.log(file);
},
//导入模板下载
downloadTemplate() {
window.location.href =this.fileDownloadUrl+"/xxxExcel导入模板.xlsx";
}
}
服务端ASP.NET Core WEB API来进行文件流数据接收和保存:
ASP.NET Core单文件和多文件上传并保存到服务端详情概述:
https://www.cnblogs.com/Can-daydayup/p/12637100.html
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FileUploadManage.Controllers
{
/// <summary>
/// 图片,视频,音频,文档等相关文件通用上传服务类
/// </summary>
public class FileUploadController : Controller
{
private static IHostingEnvironment _hostingEnvironment;
public FileUploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
/// <summary>
/// Form表单之单文件上传
/// </summary>
/// <param name="formFile">form表单文件流信息</param>
/// <returns></returns>
public JsonResult FormSingleFileUpload(IFormFile formFile)
{
var currentDate = DateTime.Now;
var webRootPath = _hostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("")
try
{
var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";
//创建每日存储文件夹
if (!Directory.Exists(webRootPath + filePath))
{
Directory.CreateDirectory(webRootPath + filePath);
}
if (formFile != null)
{
//文件后缀
var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式,拓展名
//判断文件大小
var fileSize = formFile.Length;
if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
{
return new JsonResult(new { isSuccess = false, resultMsg = "上传的文件不能大于10M" });
}
//保存的文件名称(以名称和保存时间命名)
var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf(''.'')) + "_" + currentDate.ToString("HHmmss") + fileExtension;
//文件保存
using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
{
formFile.CopyTo(fs);
fs.Flush();
}
//完整的文件路径
var completeFilePath = Path.Combine(filePath, saveName);
return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", completeFilePath = completeFilePath });
}
else
{
return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" });
}
}
catch (Exception ex)
{
return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失败,异常信息为:" + ex.Message });
}
}
}
}
原文地址https://www.cnblogs.com/Can-daydayup/p/12676870.html
asp.net-mvc – 使用CSVHelper将流输出到浏览器
该网站是基于MVC的。这里是我用来进行调用的jQuery按钮代码(数据是DTO列表的一些序列化的Json表示):
$.ajax({ type: "POST",url: unity.baseUrl + "common/ExportPayments",data: data });
这是控制器代码:
[HttpPost] public FileStreamResult ExportPayments() { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); CsvWriter writer = new CsvWriter(sw); List<Payment_dto> pd = _commonService.GetPayments(); foreach (var record in pd) { writer.WriteRecord(record); } sw.Flush(); return new FileStreamResult(ms,"text/csv"); }
这似乎完全没有实现 – 将方法步骤调用到正确的代码位置,但响应为空,更不用说为用户提供文件对话框来保存数据。我已经通过了这个代码,并且从服务中返回数据,写入它,并且不会发生错误。那我做错了什么?
编辑:返回这个…
return File(ms.GetBuffer(),"text/csv","export.csv");
…给我一个响应,包括我期望的csv格式的数据。但是浏览器似乎还不知道该怎么做 – 不会向用户提供下载选项。
解决方法
public FileStreamResult ExportPayments() { var result = WriteCsvToMemory(_commonService.GetPayments()()); var memoryStream = new MemoryStream(result); return new FileStreamResult(memoryStream,"text/csv") { FileDownloadName = "export.csv" }; } public byte[] WriteCsvToMemory(IEnumerable<Payment_dto> records) { using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var csvWriter = new CsvWriter(streamWriter)) { csvWriter.WriteRecords(records); streamWriter.Flush(); return memoryStream.ToArray(); } }
更新
以下是将复杂类型模型传递给使用GET HTTP方法的动作方法。我不喜欢这种方法,它只是给你一个想法,有一种方法来实现这一点。
模型
public class Data { public int Id { get; set; } public string Value { get; set; } public static string Serialize(Data data) { var serializer = new JavaScriptSerializer(); return serializer.Serialize(data); } public static Data Deserialize(string data) { var serializer = new JavaScriptSerializer(); return serializer.Deserialize<Data>(data); } }
行动:
[HttpGet] public FileStreamResult ExportPayments(string model) { //Deserialize model here var result = WriteCsvToMemory(GetPayments()); var memoryStream = new MemoryStream(result); return new FileStreamResult(memoryStream,"text/csv") { FileDownloadName = "export.csv" }; }
视图:
@{ var data = new Data() { Id = 1,Value = "This is test" }; } @Html.ActionLink("Export","ExportPayments",new { model = Data.Serialize(data) })
asp.net-mvc-3 – 使用csvhelper(nuGET)和C#MVC导入CSV文件
CsvHelper允许您直接将CSV文件读入自定义类.
如下所示在question之前
var streamReader = // Create a reader to your CSV file. var csvReader = new CsvReader( streamReader ); List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>();
CsvReader will automatically figure
out how to match the property names
based on the header row (this is
configurable). It uses compiled
expression trees instead of
reflection,so it’s very fast.It is also very extensible and
configurable.
我基本上试图找出如何读取带有标题(未知名称)的CSV文件并将记录读入自定义对象.
根本没有这方面的文档,所以想知道是否有人知道如何使用CsvReader将值按顺序放入字符串数组中,或者你会如何建议处理这个?
解决方法
[HttpPost] public ActionResult UploadFile(HttpPostedFileBase file) { ICsvParser csvParser = new CsvParser(new StreamReader(file.InputStream)); CsvReader csvReader = new CsvReader(csvParser); string[] headers = {}; List<string[]> rows = new List<string[]>(); string[] row; while (csvReader.Read()) { // Gets Headers if they exist if (csvReader.HasHeaderRecord && !headers.Any()) { headers = csvReader.FieldHeaders; } row = new string[headers.Count()]; for (int j = 0; j < headers.Count(); j++) { row[j] = csvReader.GetField(j); } rows.Add(row); } Importviewmodel model = new Importviewmodel(rows); return View(model); }
今天关于c# – 在文件上传时使用CSVHelper和c# multipartfile上传文件的讲解已经结束,谢谢您的阅读,如果想了解更多关于.net CsvHelper 2.0、ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件、asp.net-mvc – 使用CSVHelper将流输出到浏览器、asp.net-mvc-3 – 使用csvhelper(nuGET)和C#MVC导入CSV文件的相关知识,请在本站搜索。
本文标签: