微信抢红包活动,小爸爸27,cctv1
在 web 应用程序开发过程中,总是无法避免涉及到文件上传,这次我们来聊一聊怎么去实现一个简单方便可复用文件上传功能;通过创建自定义绑定模型来实现文件上传。
frombodyattribute fromfromattribute fromqueryattribute fromheaderattribute fromservicesattribute fromrouteattribute
[httppost] public async task<iactionresult> postinfo([frombody]userinfo user,[fromquery] string city) { ... }
public class fromfileattribute : attribute, ibindingsourcemetadata { public bindingsource bindingsource => bindingsource.formfile; }
public class userfile { public string filename { get; set; } public long length { get; set; } public string extension { get; set; } public string filetype { get; set; } private readonly static string[] filters = { ".jpg", ".png", ".bmp" }; public bool isvalid => !string.isnullorempty(this.extension) && filters.contains(this.extension); private iformfile file; public iformfile file { get { return file; } set { if (value != null) { this.file = value; this.filetype = this.file.contenttype; this.length = this.file.length; this.extension = this.file.filename.substring(file.filename.lastindexof('.')); if (string.isnullorempty(this.filename)) this.filename = this.filename; } } } public async task<string> saveas(string destinationdir = null) { if (this.file == null) throw new argumentnullexception("没有需要保存的文件"); if (destinationdir != null) directory.createdirectory(destinationdir); var newname = datetime.now.ticks; var newfile = path.combine(destinationdir ?? "", $"{newname}{this.extension}"); using (filestream fs = new filestream(newfile, filemode.createnew)) { await this.file.copytoasync(fs); fs.flush(); } return newfile; } }
[httppost] public async task<iactionresult> post([fromfile]userfile file) { if (file == null || !file.isvalid) return new jsonresult(new { code = 500, message = "不允许上传的文件类型" }); string newfile = string.empty; if (file != null) newfile = await file.saveas("/data/files/images"); return new jsonresult(new { code = 0, message = "成功", url = newfile }); }
3.2 首先是在 post([fromfile]userfile file) 中使用上面创建的 fromfileattribute 对模型 userfile 进行绑定,然后验证文件是否正确,接下来通过 file.saveas("/data/files/images"); 保存文件
3.3 上传代码非常简单,几乎到了无法精简的程度,最终发挥作用的就是 file.saveas 操作
https://files.cnblogs.com/files/viter/ron.uploadfile.zip
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论