[Route("UploadFile")]
[HttpPost]
public async Task<IHttpActionResult> UploadFile()
{
try
{
int result = 0;
bool success = true;
string error = "", path = "", filename = "", fileExt = "";
//文件保存目录路径
string saveTempPath = "/uploads/" + DateTime.Now.ToString("yyyyMMdd");
//判断目录是否存在
string dirTempPath = HttpContext.Current.Server.MapPath(saveTempPath);
if (!Directory.Exists(dirTempPath))
{
Directory.CreateDirectory(dirTempPath);
}
//设置上传目录
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(dirTempPath);
await Request.Content.ReadAsMultipartAsync(provider);// 接收数据,并保存文件
if (provider.FileData.Count > 0)
{
MultipartFileData file = provider.FileData[0];
filename = file.Headers.ContentDisposition.FileName.Trim('"');
//获取对应文件后缀名
fileExt = filename.Substring(filename.LastIndexOf(".") + 1, filename.Length - filename.LastIndexOf(".") - 1); //filename.Split('.')[1];
FileInfo fileInfo = new FileInfo(file.LocalFileName);
//fileinfo.Name 上传后的文件路径 此处不含后缀名
//修改文件名 添加后缀名
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + fileExt;
path = saveTempPath + "/" + fileName;
string saveUrl = dirTempPath + "/" + fileName;
try
{
fileInfo.MoveTo(saveUrl);
}
catch (FileLoadException ex)
{
success = false;
result = 1;
error = ex.Message;
}
}
FileResult model = new FileResult();
model.FilePath = path;
model.FileName = filename;
ajaxResult.code = result;
ajaxResult.success = success;
ajaxResult.data = model;
return Json(ajaxResult);
}
catch (Exception ex)
{
ajaxResult.code = 1;
ajaxResult.success = false;
ajaxResult.showMsg = ex.Message;
return Json(ajaxResult);
}
}
WebApi 文件上传
最新推荐文章于 2024-06-25 12:22:44 发布