HttpPostedFileBase file = Request.Files[0];
ResultMsg msg = new ResultMsg();
if (file != null)
{
if (file.ContentLength > 5242880) //判断图片大小
{
msg.Code = 0;
msg.Msg = "上传头像不允许大于5M";
}
else
{
var suff = file.FileName.Substring(file.FileName.IndexOf('.')); // 获取图片后缀名
suff = suff.ToLower();
string[] imgFormat = { ".jpg", ".png", ".bmp" }; //判断图片格式
var isImgFormat = false;
for (int i = 0; i < imgFormat.Length; i++)
{
if (suff == imgFormat[i])
{
isImgFormat = true;
break;
}
}
if (!isImgFormat) //判断图片格式
{
msg.Code = 0;
msg.Msg = "图片不符合头像指定格式!";
}
else
{
try
{
Parallel.Invoke(() =>
{
string UploadImgSavePath = @"/Images/Original/"; //原图存放路径
file.SaveAs(Server.MapPath(UploadImgSavePath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_Original" + suff));
msg.Data = UploadImgSavePath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_Original" + suff;
}, () =>
{
string ThumbnailPath = @"/Images/Thumbnail/"; //缩略图存放路径
int ThumbnaiWidth = 100; //缩略宽度
int ThumbnaiHeight = 100; //缩略高度
Image img = Image.FromStream(file.InputStream);
if (img.Width <= ThumbnaiWidth && img.Height <= ThumbnaiHeight) //如果指定浓缩图的宽高大于原图就直接保存原图
file.SaveAs(Server.MapPath(ThumbnailPath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_Thumbnail" + suff));
else
{
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(() => { return false; });
Image reduceImage = img.GetThumbnailImage(ThumbnaiWidth, ThumbnaiHeight, callb, IntPtr.Zero);
reduceImage.Save(Server.MapPath(ThumbnailPath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_Thumbnail" + suff));
}
msg.Data = ThumbnailPath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_Thumbnail" + suff;
});
msg.Code = 1;
msg.Msg = "上传成功";
}
catch (Exception ex)
{
msg.Code = 0;
msg.Msg = "错误:" + ex.Message;
}
}
}
}
else
{
msg.Code = 0;
msg.Msg = "图片丢失了,请重新尝试!";
}
return msg.SendMsg(msg);
图片上传+缩略图
最新推荐文章于 2024-06-07 16:22:34 发布