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
29 if (!di.Exists) { di.Create(); }
30
31 using (FileStream fs = System.IO.File.Create(FilePath + FileName + type))
32 {
33 // 复制文件
34 file.CopyTo(fs);
35 // 清空缓冲区数据
36 fs.Flush();
37 }
38 result = "1";
39 }
40 return result;
41 }
42 }
[HttpPost]
public async Task<string> Post()
{
string result = "";
HttpFileCollection filelist = HttpContext.Current.Request.Files;
if (filelist != null && filelist.Count > 0)
{
for (int i = 0; i < filelist.Count; i++)
{
HttpPostedFile file = filelist[i];
String Tpath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
string filename = file.FileName;
string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string FilePath = HttpContext.Current.Server.MapPath("~/" + Tpath);
string type = System.IO.Path.GetExtension(filename);
DirectoryInfo di = new DirectoryInfo(FilePath);
if (!di.Exists) { di.Create(); }
try
{
file.SaveAs(FilePath + FileName+type);
result = "1";
}
catch (Exception ex)
{
result = "上传文件写入失败:" + ex.Message;
}
}
}
else
{
result = "上传的文件信息不存在!";
}
return result;
}
前端插件:https://blog.csdn.net/u010075697/article/details/72771594
来源:oschina
链接:https://my.oschina.net/u/4264487/blog/3790752