Asp.Net Core WebApi 和Asp.Net WebApi上传文件

1.    public class UpLoadController : ControllerBase
2.     {
3.         private readonly IHostingEnvironment _hostingEnvironment;
4.  
5.         public UpLoadController(IHostingEnvironment hostingEnvironment)
6.         {
7.             _hostingEnvironment = hostingEnvironment;
8.         }
9.         [HttpPost]
10.         public async Task<string> Post([FromForm] IFormCollection formCollection)
11.         {
12.             string result = "";
13.             string webRootPath = _hostingEnvironment.WebRootPath;
14.             string contentRootPath = _hostingEnvironment.ContentRootPath;
15.  
16.             FormFileCollection filelist = (FormFileCollection)formCollection.Files;
17.  
18.             foreach (IFormFile file in filelist)
19.             {
20.                 String Tpath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
21.                 string name = file.FileName;
22.                 string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
23.                 string FilePath = webRootPath + Tpath;
24.  
25.                 string type = System.IO.Path.GetExtension(name);
26.                 DirectoryInfo di = new DirectoryInfo(FilePath);
27.  
28.                 if (!di.Exists) { di.Create(); }
29.  
30.                 using (FileStream fs = System.IO.File.Create(FilePath + FileName + type))
31.                 {
32.                     // 复制文件
33.                     file.CopyTo(fs);
34.                     // 清空缓冲区数据
35.                     fs.Flush();
36.                 }
37.                 result = ";
38.             }
39.             return result;
40.         }
41.     }

.NetCore WebApi
1. [HttpPost]
2. public async Task Post()
3. {
4. string result = “”;
5. HttpFileCollection filelist = HttpContext.Current.Request.Files;
6. )
7. {
8. ; i < filelist.Count; i++)
9. {
10. HttpPostedFile file = filelist[i];
11. String Tpath = “/” + DateTime.Now.ToString(“yyyy-MM-dd”) + “/”;
12. string filename = file.FileName;
13. string FileName = DateTime.Now.ToString(“yyyyMMddHHmmssfff”);
14. string FilePath = HttpContext.Current.Server.MapPath("~/" + Tpath);
15. string type = System.IO.Path.GetExtension(filename);
16. DirectoryInfo di = new DirectoryInfo(FilePath);
17. if (!di.Exists) { di.Create(); }
18. try
19. {
20. file.SaveAs(FilePath + FileName+type);
21. result = ";
22. }
23. catch (Exception ex)
24. {
25. result = “上传文件写入失败:” + ex.Message;
26. }
27. }
28. }
29. else
30. {
31. result = “上传的文件信息不存在!”;
32. }
33. return result;
34. }
Asp.Net WebApi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值