后台:
public string UploadImage()
{
LayuiEdit edit = new LayuiEdit();
var file = Request.Files[0];
string filepath = "";
var name = string.Empty;
name = Guid.NewGuid().ToString("N") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(file.FileName);
try
{
//文件不为空
if (file != null)
{
//创建年月文件夹,如201605
string fileFolder = DateTime.Now.ToString("yyyyMM");
//拼接保存时根路径,比如:D:Work/MVCTest/Uploads/201605
string pathForSaving = Server.MapPath("/Uploads/Image/") + fileFolder;
//判断文件夹是否存在,否则创建文件夹
if (Tool.CreateFolderIsNeeded(pathForSaving))
{
//判断上传文件的大小
if (file.ContentLength > 0)
{
//重新组合成一个存放路径,根路径+文件名称
filepath = Path.Combine(pathForSaving, name);
file.SaveAs(filepath);
}
}
//返回成功提示页面
}
//FaceModel faceModel = new FaceModel();
//faceModel.api_key = "EScZJfELRTweCi-zWxyJpU6WHDXLBI_I";
//faceModel.api_secret = "sj-N1FPF9garCXa50c_pirPRTrnm9vXd";
//faceModel.image_file = filepath;
edit.code = 0;
data data = new data();
//string baseImgUrl = filepath;
string path = HttpContext.Request.Url.Authority;
filepath = filepath.Replace("Uploads", "@");
filepath = "/Uploads" + filepath.Split('@')[1];
data.src = "http://" + path + filepath;
edit.data = new data();
edit.data = data;
//var faceResult = FaceApi(faceModel);
return JsonConvert.SerializeObject(edit);
}
catch (Exception e)
{
edit.code = 1;
edit.msg = e.Message;
data data = new data();
edit.data = new data();
edit.data = data;
return JsonConvert.SerializeObject(edit);
}
}
前台
var fileObj = document.getElementById(idFile).files[0];
$.ajax({
url: "路径",
data: {后台接收参数名:fileObj},
type: "Post",
dataType: "json",
async: true,
cache: false, //上传文件无需缓存
processData: false, //用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
beforeSend: function() {
//上传之前调用的方法
},
success: function(result) {
//成功
},
error: function() {
//失败
return;
}
})