.NET 上传文件
var data = new FormData();
data.append("ImgUrl", file);
$.ajax({
url: "", //上传图片接口地址
type: "POST",
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (res) {
//返回图片地址
}, error: function () {
alert("上传失败!");
}
});
/// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
public void UpLoadImg(HttpContext context)
{
string[] ImgType = { ".png", ".jpeg", ".jpg", ".gif", ".bmp" };
var path = UpLoadFile(ImgType);
// string result = JsonConvert.SerializeObject(path);
context.Response.Write(path);
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileTypeNames">允许上传的文件格式集合(例如:[.xls,.xlsx])</param>
/// <returns></returns>
public static string UpLoadFile(string[] fileTypeNames)
{
string serverPath = "", error = "";
HttpFileCollection filelist = HttpContext.Current.Request.Files;
if (filelist != null && filelist.Count > 0)
{
HttpPostedFile file = filelist[0];
String Tpath = "/" + DateTime.Now.ToString("yyyyMMdd").Substring(0, 6) + "/";
string filetype = file.FileName.Substring(file.FileName.LastIndexOf('.'));
if (Array.IndexOf(fileTypeNames, filetype.ToLower()) != -1)
{
string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string FilePath = HttpContext.Current.Server.MapPath("~/UploadFile" + Tpath);
DirectoryInfo di = new DirectoryInfo(FilePath);
if (!di.Exists) { di.Create(); }
try
{
file.SaveAs(FilePath + FileName + filetype);
serverPath = "/UploadFile" + Tpath + FileName + filetype;
}
catch (Exception ex)
{
error = "文件上传失败:" + ex.Message;
}
}
else error = "文件类型错误";
}
else error = "未上传任何文件";
if (error.Length > 0)
throw new Exception(error);
else
return serverPath;
}