需要实现的效果为,通过WebApi实现多文件上传功能,并且在上传时需要能附带文件说明参数,用于保存文件记录
–这里是需要的文件说明参数类
public class DistributionData
{
public string StationCodes { get; set; }
public string MaterialCodes { get; set; }
public string NetworkFileId { get; set; }
public string FileType { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public string SourceId { get; set; }
public string TypeDescribe { get; set; }
public string UserAccount { get; set; }
public string UserName { get; set; }
public string DirectoryName { get; set; }
}
Api上传方法写好之后直接ApiPost调用结果如下 调用失败后,通过参考https://www.cnblogs.com/kingCpp/p/4901268.html文章发现需要实现此效果可以通过添加【MultipartDataMediaFormatter】Nuget包
并在添加好程序包之后需要对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
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
配置好之后再次调用接口发现参数已经可以拿到了 接下来就是获取文件了,文件我们可以直接在具体的上传方法中通过System.Web.HttpContext.Current.Request.Files获取,在这里为了更加直观的看到效果,将获取文件封装为一个方法,然后通过调用此方法获取上传的文件,并放到实体参数中
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;
}
这样参数与文件就都获取到了,再就是具体上传与保存记录了
public async Task<BaseModuleResult> UploadFile(DistributionData disData, List<System.Web.HttpPostedFile> Files)
{
BaseModuleResult result = new BaseModuleResult();
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,
};
}
db.Commit();
result.data = successArr;
}
else
{
db.Rollback();
result.code = System.Net.HttpStatusCode.BadRequest;
result.info = "上传失败";
}
#endregion
}
return result;
}
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";
break;
}
FileType = _FileType;
Icon = _Icon;
}
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);
}
全部准备完毕之后再次调用 个人记录,不喜勿喷
参考文章: https://blog.csdn.net/qq_36445227/article/details/106353791 https://www.cnblogs.com/kingCpp/p/4901268.html
|