1.第一种上传方式,基本通用于.net所有的框架
[HttpPost]
[Route("Common/uploadFile1")]
public string uploads()
{
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.Request;//定义传统request对象
HttpFileCollectionBase files = request.Files;
string fileSuffix = Path.GetExtension(files[0].FileName).ToLower();
string fileId = Guid.NewGuid().ToString();
string dateKey = DateTime.Now.ToString("yyyyMMdd");
string savaPath, uri;
uri = @"/fileData/rest/" + dateKey + @"/";
savaPath = request.MapPath(uri);
if (!Directory.Exists(savaPath))
{
Directory.CreateDirectory(savaPath);
}
try
{
files[0].SaveAs(savaPath + fileId + fileSuffix);
return uri + fileId + fileSuffix;
}catch (Exception ex){
return ex.Message;
}
}
2.WebAPI可以用这个来,但是在低一点的版本没有IFormFile 这个对象
/// <summary>
/// 通用文件上传接口
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
[Route("Common/uploadFile2")]
public async Task<string> upload(IFormFile file)
{
string fileSuffix = Path.GetExtension(file.FileName).ToLower();
string fileId = Guid.NewGuid().ToString();
string dateKey = DateTime.Now.ToString("yyyyMMdd");
string savaPath,uri;
uri = @"/fileData/rest/" + dateKey + @"/";
savaPath = Path.Combine(Directory.GetCurrentDirectory(), uri);
if (!Directory.Exists(savaPath)){Directory.CreateDirectory(savaPath);}
//创建特定名称的文件流
await using var stream = new FileStream(savaPath + fileId + fileSuffix, FileMode.Create);
try
{
//上传文件
await file.CopyToAsync(stream);
stream.Flush();
return uri + fileId + fileSuffix;
} catch (Exception ex) {
//上传异常处理
return ex.Message;
}
3.上传方式,可以用于.netCore MVC方式的文件上传
[HttpPost]
public JsonResult uploadX(HttpPostedFileBase file)
{
String suffix = file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal));
string fileName = Guid.NewGuid().ToString().Replace("-", "") + suffix;
string uri = string.Format("{0}/{1}/{2}/", "fileData", "rest", DateTime.Now.Year+""+DateTime.Now.Month +""+ DateTime.Now.Day);
string filePath = Server.MapPath(string.Format("~/{0}",uri));
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
file.SaveAs(Path.Combine(filePath, fileName));
return Json(uri + fileName);
}