其实在.NET MVC中保存图片最大的问题不是如何保存图片。而是身份验证。
为什么这样说,在firefox和Chrome中最大的问题是,flash作为插件出现。从而形成了两个终端。
在这种情况下,不同的useragent使用了不同的Cookie。
SessionID也就不同了,所以作为Session来验证用户的方式,显得有些不太可行。
那么,看下思路
修改SessionID的代码,在Global.asax中
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SessionId";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
SetCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
SetCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[auth_param_name] != null)
{
SetCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
{
SetCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
}
}
catch
{
}
}
private void SetCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (null == cookie)
{
cookie = new HttpCookie(cookie_name);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}
接受Flash上传代码
[HttpPost]
public JsonResult SwfUploadImg()
{
try
{
//身份验证
if (Session["auth"] == null)
{
return Json(new { status = false, msg = "您尚未登陆!" });
}
//接受文件
HttpPostedFileBase file = Request.Files["Filedata"];
//是否文件为空
if (file == null)
{
return Json(new { status = false, msg = "上传文件为空!" });
}
//是否格式合法
if (!Common.IsAuthorizedFile(file.FileName))
{
return Json(new { status = false, msg = "上传文件格式不合法!" });
}
//检查
if (file.ContentLength >= Config.PicMaxSize)
{
return Json(new { status = false, msg = "图片超过限制!" });
}
//文件重命名
string file_name = Common.GetNewImgName(file.FileName);
//保存图片
file.SaveAs(Config.PicPath + file_name);
//返回结果
return Json(new { status = true, msg = "上传成功!", filename = file_name });
}
catch (Exception ex)
{
return Json(new { status = false, msg = "异常错误" });
Common.Log("SwfUploadImg",ex.Message);
}
}
以上只是我目前在使用的方案,如存在安全漏洞,还请指出!