1、目的及需求
需要实现的效果为,通过WebAPI实现多文件上传功能,并且在上传时需要能附带文件说明参数,用于保存文件记录
2、参数说明
这里先说明以下需要的文件说明参数类
/// <summary> /// 前端文件上传时参数数据 /// </summary> public class DistributionData { /// <summary> /// 工位编码 /// </summary> public string StationCodes { get; set; } /// <summary> /// 产品编码 /// </summary> public string MaterialCodes { get; set; } /// <summary> /// 文件ID /// </summary> public string NetworkFileId { get; set; } /// <summary> /// 文件类型 /// </summary> public string FileType { get; set; } /// <summary> /// 类型Id /// </summary> public int TypeId { get; set; } /// <summary> /// 类型名称 /// </summary> public string TypeName { get; set; } /// <summary> /// 来源Id /// </summary> public string SourceId { get; set; } /// <summary> /// 类型说明,补充文件类型 /// </summary> public string TypeDescribe { get; set; } /// <summary> /// 上传人 /// </summary> public string UserAccount { get; set; } /// <summary> /// 上传人 /// </summary> public string UserName { get; set; } /// <summary> /// 上传文件夹名称 /// </summary> public string DirectoryName { get; set; } }View Code
3、首次调用
Api上传方法写好之后直接ApiPost调用结果如下
4、添加包
调用失败后,通过参考https://www.cnblogs.com/kingCpp/p/4901268.html文章发现需要实现此效果可以通过添加【MultipartDataMediaFormatter】Nuget包
5、配置
添加包之后需要对Api进行配置
public static class WebApiConfig { public static void Register(HttpConfiguration config) { #region 为了实现文件上传的同时带参数,配置MultipartDataMediaFormatter GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new MultipartDataMediaFormatter.FormMultipartEncodedMediaTypeFormatter()); #endregion // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }View Code
配置好之后再次调用接口发现参数已经可以拿到
6、文件获取
接下来就是获取文件了,文件我们可以直接在具体的上传方法中通过System.Web.HttpContext.Current.Request.Files获取,在这里为了更加直观的看到效果,将获取文件封装为一个方法,然后通过调用此方法获取上传的文件,并放到实体参数中
/// <summary> /// 获取文件上传集合 /// </summary> /// <returns></returns> public static List<System.Web.HttpPostedFile> GetFileList() { if (System.Web.HttpContext.Current.Request.Files.Count == 0) { return null; } List<System.Web.HttpPostedFile> res = new List<System.Web.HttpPostedFile>(); for (int i = 0; i < System.Web.HttpContext.Current.Request.Files.Count; i++) { res.Add(System.Web.HttpContext.Current.Request.Files[i]); } return res; }View Code
7、具体实现
这样参数与文件就都获取到了,再就是具体上传与保存记录了
接口返回数据格式如下:
上传文件具体方法:
/// <summary> /// 上传文件 /// </summary> /// <param name="disData"></param> /// <returns></returns> public async Task<BaseModuleResult> UploadFile(DistributionData disData, List<System.Web.HttpPostedFile> Files) { BaseModuleResult result = new BaseModuleResult(); //Thread.Sleep(1000); List<Entity.Base_NetworkFile> list = new List<Entity.Base_NetworkFile>(); ///文件上传地址 var UploadFileUrl = ConfigHelper.AppSettings("staticfilesLocal"); int IsOk = 0; if (Files.Count > 0) { IDatabase db = DataFactory.Database(); DbTransaction transaction = db.BeginTrans(); for (int i = 0; i < Files.Count; i++) { var files = Files[i]; string FileEextension = System.IO.Path.GetExtension(files.FileName); //获取文件类型、文件图标 this.DocumentType(FileEextension, out string FileType, out string Icon); #region 文件上传地址 string fullFileName = string.Empty; if (!string.IsNullOrWhiteSpace(disData.DirectoryName)) { fullFileName = $"{UploadFileUrl}/{disData.DirectoryName}/{DateTime.Now.ToString("yyyyMMdd")}/{CommonHelper.GetGuid}{FileEextension}"; } else { fullFileName = $"{UploadFileUrl}/{DateTime.Now.ToString("yyyyMMdd")}/{CommonHelper.GetGuid}{FileEextension}"; } #endregion #region 文件夹目录处理 string path = System.IO.Path.GetDirectoryName(fullFileName); if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } #endregion #region 开始上传 if (!System.IO.File.Exists(fullFileName)) { byte[] byteImage = new byte[files.InputStream.Length]; files.InputStream.Read(byteImage, 0, byteImage.Length); files.InputStream.Seek(0, System.IO.SeekOrigin.Begin); try { Entity.Base_NetworkFile entity = new Entity.Base_NetworkFile(); //保存文件记录表相关数据 Save_NetworkFile(disData, files.FileName, files.ContentLength.ToString(), FileEextension, Icon, FileType, fullFileName, UploadFileUrl, db, transaction, ref IsOk, ref entity); if (IsOk > 0) { list.Add(entity); files.SaveAs($"{fullFileName}"); } } catch (Exception ex) { IsOk = 0; db.Rollback(); System.IO.File.Delete(fullFileName); result.info = ex.Message; return result; } } #endregion } #region 组装返回数据 //文件记录不为空并且=文件数,已确认所有文件上传成功 if (list != null && list.Any() && list.Count == Files.Count) { result.code = System.Net.HttpStatusCode.OK; result.info = "已上传成功"; object[] successArr = new object[list.Count]; for (int i = 0; i < list.Count; i++) { successArr[i] = new { FileName = list[i].FileName, FilePath = list[i].FilePath, //这里是拼接一个网络路径的方法 NewWorkPath = UploadHelper.HttpRelativePathToNetWorkURL(list[i].FilePath), NewWorkFileID = list[i].NetworkFileId,//文件记录Id }; } db.Commit(); result.data = successArr; } else { db.Rollback(); result.code = System.Net.HttpStatusCode.BadRequest; result.info = "上传失败"; } #endregion } return result; }View Code
/// <summary> /// 获取文件类型、文件图标 /// </summary> /// <param name="Eextension">后缀名</param> /// <param name="FileType">要返回文件类型</param> /// <param name="Icon">要返回文件图标</param> private void DocumentType(string Eextension, out string FileType, out string Icon) { string _FileType = ""; string _Icon = ""; switch (Eextension) { case ".docx": _FileType = "word"; _Icon = "doc"; break; case ".doc": _FileType = "word"; _Icon = "doc"; break; case ".xlsx": _FileType = "excel"; _Icon = "xls"; break; case ".xls": _FileType = "excel"; _Icon = "xls"; break; case ".pptx": _FileType = "ppt"; _Icon = "ppt"; break; case ".ppt": _FileType = "ppt"; _Icon = "ppt"; break; case ".txt": _FileType = "txt"; _Icon = "txt"; break; case ".pdf": _FileType = "pdf"; _Icon = "pdf"; break; case ".zip": _FileType = "rar"; _Icon = "zip"; break; case ".rar": _FileType = "rar"; _Icon = "rar"; break; case ".png": _FileType = "image"; _Icon = "png"; break; case ".bmp": _FileType = "image"; _Icon = "bmp"; break; case ".gif": _FileType = "image"; _Icon = "gif"; break; case ".jpg": _FileType = "image"; _Icon = "jpeg"; break; case ".mp3": _FileType = "mp3"; _Icon = "mp3"; break; case ".html": _FileType = "html"; _Icon = "html"; break; case ".css": _FileType = "css"; _Icon = "css"; break; case ".mpeg": _FileType = "video"; _Icon = "mpeg"; break; case ".mov": _FileType = "video"; _Icon = "mov"; break; case ".mp4": _FileType = "video"; _Icon = "mp4"; break; case ".pds": _FileType = "pds"; _Icon = "pds"; break; case ".ttf": _FileType = "ttf"; _Icon = "ttf"; break; case ".swf": _FileType = "video"; _Icon = "swf"; break; default: _FileType = "other"; _Icon = "new"; //return "else.png"; break; } FileType = _FileType; Icon = _Icon; }View Code
/// <summary> /// 保存文件表相关数据 /// </summary> /// <param name="disData"></param> /// <param name="fileName"></param> /// <param name="ContentLength"></param> /// <param name="FileEextension"></param> /// <param name="Icon"></param> /// <param name="FileType"></param> /// <param name="fullallname"></param> /// <param name="hostPath"></param> /// <param name="db"></param> /// <param name="transaction"></param> /// <param name="IsOk"></param> /// <param name="entity"></param> private void Save_NetworkFile(DistributionData disData, string fileName, string ContentLength, string FileEextension, string Icon, string FileType, string fullallname, string hostPath, IDatabase db, DbTransaction transaction, ref int IsOk, ref Entity.Base_NetworkFile entity) { entity = new Entity.Base_NetworkFile(); //文件记录信息写入数据库 entity.NetworkFileId = CommonHelper.GetGuid; entity.CreateDate = DateTime.Now; entity.CreateUserId = disData.UserAccount; entity.CreateUserName = disData.UserName; entity.FolderId = disData.StationCodes; entity.FileName = fileName; entity.FilePath = fullallname.Replace(hostPath, ""); entity.FileSize = ContentLength; entity.FileExtensions = FileEextension; entity.Icon = Icon; entity.FileType = FileType; entity.Enabled = 1; entity.SourceId = disData.SourceId; entity.Type = disData.TypeId; entity.TypeDescribe = disData.TypeDescribe; IsOk = db.Insert(entity, transaction); }View Code
8、最终效果
全部准备完毕之后再次调用
标签:WebAPi,case,string,附带,FileType,entity,break,上传,Icon From: https://www.cnblogs.com/lwk9527/p/17373631.html