本文实例为大家分享了ASP.NET Core实现文件上传和下载的具体代码,供大家参考,具体内容如下 一、文件上传 1.1 获取文件后缀
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/// <summary> /// 获取文件后缀 /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> public async static Task<string> GetFileSuffixAsync(string fileName) { return await Task.Run(() => { string suffix = Path.GetExtension(fileName); return suffix; }); } |
1.2 上传单文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
public class FileMessage { /// <summary> /// 原文件名称 /// </summary> public string FileName { get; set; } /// <summary> /// 附件名称(协议或其他要进行数据库保存与模型绑定的命名) /// </summary> public string ArgumentName { get; set; } /// <summary> /// 文件大小(KB) /// </summary> public string FileSize { get; set; } /// <summary> /// -1:上传失败 0:等待上传 1:已上传 /// </summary> public int FileStatus { get; set; } /// <summary> /// 上传结果 /// </summary> public string UploadResult { get; set; } /// <summary> /// 创建实例 /// </summary> /// <param name="fileName">原文件名称</param> /// <param name="argumentName">(新)附件名称</param> /// <param name="fileSize">大小</param> /// <param name="fileStatus">文件状态</param> /// <returns></returns> public static FileMessage CreateNew(string fileName, string argumentName, string fileSize, int fileStatus, string uploadResult) { return new FileMessage() { FileName = fileName, ArgumentName = argumentName, FileSize = fileSize, FileStatus = fileStatus, UploadResult = uploadResult }; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/// <summary> /// 上传文件 /// </summary> /// <param name="file">上传的文件</param> /// <param name="fold">要存储的文件夹</param> /// <returns></returns> public async static Task<FileMessage> UploadFileAsync(IFormFile file, string fold) { string fileName = file.FileName; string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await GetFileSuffixAsync(file.FileName); string fileSize = Math.Round((decimal)file.Length / 1024, 2) + "k"; string filePath = Path.Combine(path, argumentName); try { using (FileStream stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } return FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功"); } catch (Exception e) { return FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败:" + e.Message); } } |
1.3 上传多文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/// <summary> /// 上传多文件 /// </summary> /// <param name="files">上传的文件集合</param> /// <param name="fold">要存储的文件夹</param> /// <returns></returns> public async static Task<List<FileMessage>> UploadFilesAsync(IFormFileCollection files, string fold) { string path = Directory.GetCurrentDirectory() + @"/Upload/" + fold + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } List<FileMessage> messages = new List<FileMessage>(); foreach (var file in files) { string fileName = file.FileName; string argumentName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + await GetFileSuffixAsync(file.FileName); string fileSize = Math.Round((decimal)file.Length / 1024, 2) + "k"; string filePath = Path.Combine(path, argumentName); try { using (FileStream stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, 1, "文件上传成功")); } catch (Exception e) { messages.Add(FileMessage.CreateNew(fileName, argumentName, fileSize, -1, "文件上传失败,失败原因:" + e.Message)); } } return messages; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
[Route("api/[controller]")] [ApiController] public class ManageProtocolFileController : ControllerBase { private readonly string createName = ""; private readonly IWebHostEnvironment _env; private readonly ILogger<ManageProtocolFileController> _logger; public ManageProtocolFileController(IWebHostEnvironment env, ILogger<ManageProtocolFileController> logger) { _env = env; _logger = logger; } /// <summary> /// 协议上传附件 /// </summary> /// <param name="file"></param> /// <returns></returns> [HttpPost("upload")] public async Task<FileMessage> UploadProtocolFile([FromForm] IFormFile file) { return await UploadFileAsync(file, "ManageProtocol"); } } |
二、文件下载 2.1 获取ContentType属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/// <summary> /// 获取文件ContentType /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> public async static Task<string> GetFileContentTypeAsync(string fileName) { return await Task.Run(() => { string suffix = Path.GetExtension(fileName); var provider = new FileExtensionContentTypeProvider(); var contentType = provider.Mappings[suffix]; return contentType; }); } |
2.2 执行下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
[Route("api/[controller]")] [ApiController] public class ManageProtocolFileController : ControllerBase { private readonly string createName = ""; private readonly IWebHostEnvironment _env; private readonly ILogger<ManageProtocolFileController> _logger; public ManageProtocolFileController(IWebHostEnvironment env, ILogger<ManageProtocolFileController> logger) { _env = env; _logger = logger; } /// <summary> /// 下载附件 /// </summary> /// <param name="fileName">文件名称</param> /// <returns></returns> [HttpGet("download")] public async Task<FileStreamResult> Download([FromQuery] string fileName) { try { string rootPath = _env.ContentRootPath + @"/Upload/ManageProtocolFile"; string filePath = Path.Combine(rootPath, fileName); var stream = System.IO.File.OpenRead(filePath); string contentType = await GetFileContentTypeAsync(fileName); _logger.LogInformation("用户:" + createName + "下载后台客户协议附件:" + request.FileName); return File(stream, contentType, fileName); } catch (Exception e) { _logger.LogError(e, "用户:" + createName + "下载后台客户协议附件出错,出错原因:" + e.Message); throw new Exception(e.ToString()); } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。 from:http://news.558idc.com/448616.html
View Details有时候我们在写webapi的时候,不想把正常用的对象所有字段都返回,我们需要进行一些筛选,忽略某些字段,大概说一下几种方法
方法一:给不同需求单独写查询,提供不同的数据对象
单独写一个model,然后单独写一个查询,在通过接口提供出去
这种方法效率比较高,不需要单独解析一下,就是代码量多一点,适用于变化不大的情况。
当然也可能是这个接口是需要依赖与另外一个接口返回的数据,道理是一样,就是对数据源加工后进去返回,至于数据源是数据库还是缓存还是其他接口提供的数据不影响我们数据加工几种方法的使用
方法二:使用对象映射
单独写一个model,把原有model赋值到另外的对象,使用automapper或者自己通过反射映射一下对象即可 这样写法要通过反射转化一遍,效率会慢一点,但是可以共用一个查询方法。
想要修改字段名可以自己弄一个映射关系,用特性或者动态映射都可以,automapper映射一个名字还是比较方便的
方法三:通过Newtonsoft.Json在model中配置忽略某些值即可
通过JsonIgnore特性配置即可。
View DetailsJava 语言按照错误严重性,从 throwale 根类衍生出 Error 和 Exception 两大派系。
Error(错误):
程序在执行过程中所遇到的硬件或操作系统的错误。错误对程序而言是致命的,将导致程序无法运行。常见的错误有内存溢出,jvm 虚拟机自身的非正常运行,calss 文件没有主方法。程序本生是不能处理错误的,只能依靠外界干预。Error 是系统内部的错误,由 jvm 抛出,交给系统来处理。
Exception(异常):
程序正常运行中,可以预料的意外情况。比如数据库连接中断,空指针,数组下标越界。异常出现可以导致程序非正常终止,也可以预先检测,被捕获处理掉,使程序继续运行。Exception(异常)按照性质,又分为编译异常(受检异常)和运行时异常(非受检异常)。
◦ 编译异常:
又叫可检查异常,通常时由语法错和环境因素(外部资源)造成的异常。比如输入输出异常 IOException,数据库操作 SQLException。其特点是,Java 语言强制要求捕获和处理所有非运行时异常。通过行为规范,强化程序的健壮性和安全性。
◦ 运行时异常:
又叫不检查异常 RuntimeException,这些异常一般是由程序逻辑错误引起的,即语义错。比如算术异常,空指针异常 NullPointerException,下标越界 IndexOutOfBoundsException。运行时异常应该在程序测试期间被暴露出来,由程序员去调试,而避免捕获。
View Details这篇文章给大家分享的是有关C#如何使用NPOI设置Excel下拉选项的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。 第一种 · 直接设置下拉值,不超过255个字符(优点:逻辑简单 ;缺点:有字符限制) · 适用于下拉值为固定值,例如:状态、性别等 方法块:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void SetCellDropdownList(ISheet sheet, int firstcol, int lastcol, string[] vals) { //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(1, 65535, firstcol, lastcol); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(vals); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } |
调用:
1 2 3 |
HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("sheet1"); ExcelHelper.SetCellDropdownList(sheet, 1, 1, new List<string>() { "男", "女", "保密" }.ToArray()); |
第二种 · 通过绑定值到sheet中设置下拉 · 适用于数据较多,或灵活控制的值,例如:城市区域、数据表信息等。 方法块:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public static void SetCellDropdownList(HSSFWorkbook workbook, ISheet sheet, string name, int firstcol, int lastcol, string[] vals, int sheetindex = 1) { //先创建一个Sheet专门用于存储下拉项的值 ISheet sheet2 = workbook.CreateSheet(name); //隐藏 workbook.SetSheetHidden(sheetindex, true); int index = 0; foreach (var item in vals) { sheet2.CreateRow(index).CreateCell(0).SetCellValue(item); index++; } //创建的下拉项的区域: var rangeName = name + "Range"; IName range = workbook.CreateName(); range.RefersToFormula = name + "!$A$1:$A$" + index; range.NameName = rangeName; CellRangeAddressList regions = new CellRangeAddressList(0, 65535, firstcol, lastcol); DVConstraint constraint = DVConstraint.CreateFormulaListConstraint(rangeName); HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } |
调用:
1 2 3 4 |
HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("sheet1"); var roomTypeList = GetRoomTypeNameList(); ExcelHelper.SetCellDropdownList(workbook, sheet, "RoomTypeDictionary", 1, 1, roomTypeList.ToArray()); |
另外,延伸联动下拉(直接贴源码了) 方法块:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
private void SetCityCellDropdownList(HSSFWorkbook workbook, ISheet sheet, string dictionaryName, int citycol, int areacol, int sheetIndex) { var citylist = GetCityList(); int citycount = citylist.Count; ISheet sheet2 = workbook.CreateSheet(dictionaryName); //隐藏 workbook.SetSheetHidden(sheetIndex, true); #region 城市区域数据构造 //城市 int rowIndex = 0; foreach (var item in citylist) { IRow row = sheet2.CreateRow(rowIndex); row.CreateCell(0).SetCellValue(item.Name); rowIndex++; } //区域 int n_rowIndex = 0; foreach (var item in citylist) { int areaIndex = 0; foreach (var area in item.AreaList) { IRow row = sheet2.GetRow(areaIndex); if (row == null) { row = sheet2.CreateRow(areaIndex); } row.CreateCell(n_rowIndex + 1).SetCellValue(area.Name); areaIndex++; } n_rowIndex++; } #endregion #region 设置数据字段范围 //定义城市 int columnIndex = 1; IName range_Country = workbook.CreateName(); range_Country.RefersToFormula = string.Format("{0}!${1}$1:${1}${2}", dictionaryName, GetExcelColumnName(columnIndex), citycount); range_Country.NameName = "城市"; //定义区 foreach (var item in citylist) { int areacount = item.AreaList.Count; columnIndex++; IName range_area = workbook.CreateName(); range_area.RefersToFormula = string.Format("{0}!${1}$1:${1}${2}", dictionaryName, GetExcelColumnName(columnIndex), areacount); range_area.NameName = item.Name; } //城市列表下拉绑定 ExcelHelper.SetCellDropdownList(sheet, 1, 65535, citycol, citycol, "城市"); //第二列,跟随第一列联动 string colName = GetExcelColumnName(areacol); for (int j = 1; j < 500; j++) { ExcelHelper.SetCellDropdownList(sheet, j, j, areacol, areacol, string.Format("INDIRECT(${0}${1})", colName, j + 1)); } #endregion } private string GetExcelColumnName(int columnNumber) { int dividend = columnNumber; string columnName = String.Empty; int modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnName = Convert.ToChar(65 + modulo).ToString() + columnName; dividend = (int)((dividend - modulo) / 26); } return columnName; } |
1 2 3 4 5 6 7 8 |
public static void SetCellDropdownList(ISheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, string name) { CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol); DVConstraint constraint = DVConstraint.CreateFormulaListConstraint(name); HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。"); sheet.AddValidationData(dataValidate); } |
调用:
1 2 3 |
HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("sheet1"); SetCityCellDropdownList(workbook, sheet, "CityDictionary", 1, 2, 1); |
from:https://www.yisu.com/zixun/688759.html
View Details1、添加下拉框,并开启列值校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/// <summary> /// 添加下拉框,并开启列值校验 /// </summary> public static void SetCellDropdownList(XSSFSheet sheet, int firstcol, int lastcol, List<string> vals) { //设置 下拉框内容 var dvHelper = new XSSFDataValidationHelper(sheet); var dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateExplicitListConstraint(vals.ToArray()); //设置下拉框对应的行范围、列范围,行和列都是从0开始 var addressList = new CellRangeAddressList(0, 65535, firstcol, lastcol); var validation = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, addressList); //开启下拉框 validation.ShowPromptBox = true; //开启错误提醒 validation.ShowErrorBox = true; sheet.AddValidationData(validation); } |
2、调用方
1 2 3 4 5 6 7 8 |
public static void main() { var workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("sheet1"); var validateList=new List<string>(){"选项1","选项2","选项3"}; SetCellDropdownList(sheet, 2, 2, validateList) } |
from:https://blog.csdn.net/a304954732/article/details/127220912
View Details使用NuGet安装NPOI,添加以下命名空间
1 2 3 4 |
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; |
添加类 ExcelExporter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
public static class ExcelExporter { /// <summary> /// DataTable导出Excel /// </summary> /// <param name="dataTable">数据源</param> /// <param name="fileName">保存的文件名</param> /// <param name="sheetName">表名</param> public static void ExportToExcel(this DataTable dataTable, string fileName, string sheetName = "Sheet1") { if (dataTable == null || dataTable.Rows.Count == 0) throw new Exception("No data to export"); ISheet sheet = null; IWorkbook workbook = null; try { using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); else throw new NotSupportedException("Not supported file extension"); if (string.IsNullOrEmpty(sheetName)) sheetName = "Sheet1"; sheet = workbook.CreateSheet(sheetName); ICellStyle headerStyle = workbook.CreateCellStyle(); //首行填充黄色 headerStyle.FillForegroundColor = IndexedColors.Yellow.Index; headerStyle.FillPattern = FillPattern.SolidForeground; IRow row = sheet.CreateRow(0); for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { var cell = row.CreateCell(columnIndex); cell.CellStyle = headerStyle; cell.SetCellValue(dataTable.Columns[columnIndex].ColumnName); //设置列名 } for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++) { row = sheet.CreateRow(rowIndex + 1); for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { row.CreateCell(columnIndex).SetCellValue(Convert.ToString(dataTable.Rows[rowIndex][columnIndex])); } } for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { sheet.AutoSizeColumn(columnIndex); //自适应宽度 } sheet.SetAutoFilter(new CellRangeAddress(0, 0, 0, dataTable.Columns.Count - 1)); //首行筛选 sheet.CreateFreezePane(dataTable.Columns.Count, 1); //首行冻结 workbook.Write(fs); //写入到excel } } finally { if (workbook != null) workbook.Close(); } } } |
使用时传入文件路径,即可将DataTable导出到指定位置。 如要导出集合类数据IEnumerable<T>,使用反射转成DataTable即可。方法大同小异,这里就不写了 from:https://www.qyyshop.com/info/813140.html
View Details当本地没有安装Excel,但是又想导出Excel,采用Office插件是行不通的,NPOI是导出Excel的一个开源的插件。在导出Excel后,为了方便阅读,可以才采用自适应列宽的方式使得单元格的宽度和文本的宽度接近。NPOI中工作簿ISheet有自适应列宽的方法,但是其效果列宽还是比单元中文字的宽度稍微大一点。此时我们可以自己计算其宽度,自定义列宽。一下这种方式是支持中英文以及数字的。
View Details每次用到这个都要去百度,这里记录一下,xls和xlsx两种格式设置背景颜色的区别,这里省略了前面读取模板或者创建excel的过程: xls:
1 2 3 4 5 6 7 8 9 10 11 |
ICellStyle style = workbook.CreateCellStyle(); //使用NPOI已经有的颜色创建 style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; style.FillPattern = FillPattern.SolidForeground; //没有的颜色,使用RGB值进行创建 //这里要自定义一个颜色板覆盖掉原来的index,这里覆盖48号位置上的 HSSFPalette palette = ((HSSFWorkbook)workbook).GetCustomPalette(); palette.SetColorAtIndex(48, 0, 112, 192); style.FillForegroundColor = palette.FindColor(0, 112, 192).Indexed; |
xlsx:
1 2 3 4 5 6 7 8 9 10 |
ICellStyle style = workbook.CreateCellStyle(); //使用NPOI已经有的颜色创建(这里跟xls一样,不知道为什么可以通用) style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; style.FillPattern = FillPattern.SolidForeground; //使用没有的颜色,这里和xls不一样,不需要覆盖掉原来的色板 style.FillForegroundColor = 0; style.FillPattern = FillPattern.SolidForeground; ((XSSFColor)style.FillForegroundColorColor).SetRgb(new byte[] { 0, 176, 240 }); |
from:https://blog.csdn.net/qq_34452824/article/details/119379559
View DetailsNPOI生产.xlsx文件件时,在使用book.Write(ms);后,会关闭流,这样导致再次使用Respons输出流的时候就出错了。 我看到一些网友提供的解决办法是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class NPOIMemoryStream : MemoryStream { /// <summary> /// 获取流是否关闭 /// </summary> public bool IsColse { get; private set; } public NPOIMemoryStream(bool colse = false) { IsColse = colse; } public override void Close() { if (IsColse) { base.Close(); } } } |
使用自定义流代替内存流,这样就可以保证流不会被自定关闭了 from:https://www.cnblogs.com/caoyc/p/6215210.html
View Details