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