[HttpPost]
public ActionResult Upload()
{
try
{
var file = Request.Files[0];
var filecombin = file.FileName.Split(‘.‘);
if (file == null || String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0 || filecombin.Length < 2)
{
return Json(new
{
fileid = 0,
src = "",
name = "",
msg = "上传出错 请检查文件名 或 文件内容"
});
}
//定义本地路径位置
string local = "Upload\\" + System.DateTime.Now.ToString("yyyy-MM-dd");
string filePathName = string.Empty;
string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, local);
var tmpName = Server.MapPath("~/Upload/" + System.DateTime.Now.ToString("yyyy-MM-dd") + "/");
var tmp = file.FileName;
var tmpIndex = 0;
//判断是否存在相同文件名的文件 相同累加1继续判断
while (System.IO.File.Exists(tmpName + tmp))
{
tmp = filecombin[0] + "_" + ++tmpIndex + "." + filecombin[1];
}
//不带路径的最终文件名
filePathName = tmp;
if (!System.IO.Directory.Exists(localPath))
System.IO.Directory.CreateDirectory(localPath);
string localURL = Path.Combine(local, filePathName);
file.SaveAs(Path.Combine(localPath, filePathName)); //保存图片(文件夹)
return Json(new
{
src = localURL.Trim().Replace("\\", "/"),
name = Path.GetFileNameWithoutExtension(file.FileName), // 获取文件名不含后缀名
msg = "上传成功",
fileName = "~/Upload/" + System.DateTime.Now.ToString("yyyy-MM-dd") + "/" + filePathName//最终返回的路径及文件名称
});
}
catch { }
return Json(new
{
src = "",
name = "", // 获取文件名不含后缀名
msg = "上传出错",
fileName = ""
});
}
原文地址:https://www.cnblogs.com/lhl123/p/10936387.html