上传图片(MVC和MVC3两种)

【MVC第一种】

Tools.cs:

View Code
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;

namespace www.landglass.com.Tools
{
publicstaticclass Tool
{
privatestaticreadonlystring APPLICATIONPATH = System.AppDomain.CurrentDomain.BaseDirectory;

publicstaticstring GetGuid()
{
return Guid.NewGuid().ToString().Replace("-", "").ToUpper();
}
#region 上传图片、文件代码
privatedelegatebool FileIsValidHandler(string suffix);
publicenum UploadingFileType
{
Docuemnt,
Image
}
privatestaticbool ImageFileIsValid(string suffix)
{
switch (suffix)
{
case"jpg":
returntrue;
case"jpeg":
returntrue;
case"bmp":
returntrue;
case"gif":
returntrue;
case"png":
returntrue;
default:
returnfalse;
}
}
privatestaticbool DocumentFileIsValid(string suffix)
{
switch (suffix)
{
case"xls":
returntrue;
case"ppt":
returntrue;
case"doc":
returntrue;
case"xlsx":
returntrue;
case"pptx":
returntrue;
case"docx":
returntrue;
case"pdf":
returntrue;
case"txt":
returntrue;
case"rar":
returntrue;
default:
returnfalse;
}
}
privatestaticbool FileIsValid(string suffix,FileIsValidHandler handler)
{
return handler(suffix);
}
///<summary>
/// 删除图片或者文件
///</summary>
publicstaticbool DeleteFile(string filename, string virtualPath)
{
string filePath = APPLICATIONPATH +@"\"+ virtualPath +@"\"+ filename;
try
{
if (File.Exists(filePath))
File.Delete(filePath);
returntrue;
}
catch (Exception ex)
{
throw ex;
}
}
///<summary>
/// 文件存储
///</summary>
publicstaticbool UploadFileToServer(UploadingFileType type, HttpPostedFile file, string virtualPath, string id, outstring newFileName)
{
newFileName
=string.Empty;
if (file !=null&&!string.IsNullOrEmpty(file.FileName) && file.ContentLength <=300000)
{
bool flag = ValidateFileAndGetName(type, file, id, out newFileName);
if (flag)
file.SaveAs(APPLICATIONPATH
+ virtualPath +@"\"+ newFileName);
return flag;
}

returnfalse;
}
///<summary>
/// 验证上传文件是否合法并设置获取新的文件名
///</summary>
privatestaticbool ValidateFileAndGetName(UploadingFileType type,HttpPostedFile file, string id,outstring newFileName)
{
id
=string.IsNullOrEmpty(id) ? GetGuid() : id;
int index = file.FileName.LastIndexOf(".");
string suffix = file.FileName.Substring(index +1).Trim().ToLower();
newFileName
=string.Format("{0}.{1}", id, suffix);

switch (type)
{
case UploadingFileType.Docuemnt:
return FileIsValid(suffix, DocumentFileIsValid);
case UploadingFileType.Image:
return FileIsValid(suffix, ImageFileIsValid);
default:
returnfalse;
}
}
#endregion
}
}

controller.cs

View Code
///<summary>
/// 执行添加/修改产品信息操作
///</summary>
///<param name="additionalDocFile">文件</param>
///<param name="additionalImgFile">图片</param>
publicvoid SubmitSave(HttpPostedFile additionalDocFile, HttpPostedFile additionalImgFile)
{
CancelLayoutAndView();
Product product
=new Product();
BindObjectInstance(product, ParamStore.Form,
"product");
bool isUpdate =false;
if (string.IsNullOrEmpty(product.ID))//如果id存在,执行修改
{
product.ID
= Tool.GetGuid();
}
else
{
isUpdate
=true;
}
#region Uploading Files
bool flagUploadFile =true;
if (additionalImgFile !=null&&!string.IsNullOrEmpty(additionalImgFile.FileName))//修改图片
{
string imgUrl =string.Empty;
flagUploadFile
= Tool.UploadFileToServer(Tool.UploadingFileType.Image, additionalImgFile, PRODUCTIMAGES, product.ID, out imgUrl);
if (flagUploadFile)
{
product.ProductImgUrl
= imgUrl;
}
else
{
Response.Write(
string.Format("<script type='text/javascript'>alert('上传图片失败!');history.go(-1);</script>"));
return;
}
}
if (additionalDocFile !=null&&!string.IsNullOrEmpty(additionalDocFile.FileName))//修改文件
{
string imgUrl =string.Empty;
flagUploadFile
= Tool.UploadFileToServer(Tool.UploadingFileType.Docuemnt, additionalDocFile, PRODUCTDECUMENTS, product.ID, out imgUrl);
if (flagUploadFile)
{
product.ProductDocUrl
= imgUrl;
}
else
{
Response.Write(
string.Format("<script type='text/javascript'>alert('上传文件失败!');history.go(-1);</script>"));
return;
}
}
#endregion
bool flag = isUpdate ? _pModel.Update(product) : _pModel.Add(product);
if (!isUpdate &&!flag)
{
Tool.DeleteFile(product.ProductImgUrl, PRODUCTIMAGES);
Tool.DeleteFile(product.ProductDocUrl, PRODUCTDECUMENTS);
}
Response.Write(
string.Format("<script type='text/javascript'>alert('成功!');window.location.href='index.aspx';</script>"));
}

页面.vm

View Code
<form action="SubmitSave.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="additionalImgFile"/>
#if($product.ProductImgUrl!="")
<input type="hidden" name="product.ProductImgUrl" value="$!{product.ProductImgUrl}"/>
<img id="product.ProductImgUrl" name="product.ProductImgUrl" width="100px" height="50px" src="$!SiteRoot/UploadFiles/ProductImages/$!{product.ProductImgUrl}"/>
#end
</form>

生成缩略图.cs

View Code
#region 生成缩略图
///<summary>
/// 生成缩略图,[Author]落叶十九,[UpdateTime]2010-12-30
///</summary>
///<param name="originalImagePath">源图路径(物理路径)</param>
///<param name="thumbnailPath">缩略图路径(物理路径)</param>
///<param name="width">缩略图宽度</param>
///<param name="height">缩略图高度</param>
///<param name="mode">生成缩略图的方式</param>
publicstaticvoid MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
Image originalImage
=Image.FromFile(originalImagePath);

int towidth = width;
int toheight = height;

int x =0;
int y =0;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case"HW"://指定高宽缩放(可能变形)
break;
case"W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case"H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case"Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh
= originalImage.Height;
ow
= originalImage.Height * towidth / toheight;
y
=0;
x
= (originalImage.Width - ow) /2;
}
else
{
ow
= originalImage.Width;
oh
= originalImage.Width * height / towidth;
x
=0;
y
= (originalImage.Height - oh) /2;
}
break;
default:
break;
}
//新建一个bmp图片
System.Drawing.Image bitmap =new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);

try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
#endregion

删除文件或者图片.cs

View Code
publicbool DeleteImages(string imgUrl)
{
try
{
string basePath = System.AppDomain.CurrentDomain.BaseDirectory + _uploadpath;
string filePath = basePath +@"\"+ imgUrl;
string thumbFilePath = basePath +@"\s_"+ imgUrl;
if(File.Exists(filePath))
File.Delete(filePath);
if(File.Exists(thumbFilePath))
File.Delete(thumbFilePath);
returntrue;
}
catch (Exception ex)
{
throw ex;
}
}

[MVC3上传图片]

Tools.cs

View Code
publicstaticstring GetGuid()
{
return Guid.NewGuid().ToString().Replace("-", "").ToUpper();
}
#region 上传图片、文件代码
privatedelegatebool FileIsValidHandler(string suffix);
publicenum UploadingFileType
{
Docuemnt,
Image
}
privatestaticbool ImageFileIsValid(string suffix)
{
switch (suffix)
{
case"jpg":
returntrue;
case"jpeg":
returntrue;
case"bmp":
returntrue;
case"gif":
returntrue;
case"png":
returntrue;
default:
returnfalse;
}
}
privatestaticbool DocumentFileIsValid(string suffix)
{
switch (suffix)
{
case"xls":
returntrue;
case"ppt":
returntrue;
case"doc":
returntrue;
case"xlsx":
returntrue;
case"pptx":
returntrue;
case"docx":
returntrue;
case"pdf":
returntrue;
case"txt":
returntrue;
case"rar":
returntrue;
default:
returnfalse;
}
}
privatestaticbool FileIsValid(string suffix, FileIsValidHandler handler)
{
return handler(suffix);
}
///<summary>
/// 删除图片或者文件
///</summary>
publicstaticbool DeleteFile(string filename, string virtualPath)
{
string filePath = APPLICATIONPATH +@"\"+ virtualPath +@"\"+ filename;
try
{
if (File.Exists(filePath))
File.Delete(filePath);
returntrue;
}
catch (Exception ex)
{
throw ex;
}
}
///<summary>
/// 文件存储
///</summary>
publicstaticbool UploadFileToServer(UploadingFileType type, HttpPostedFileBase file, string virtualPath, string id, outstring newFileName)
{
newFileName
=string.Empty;
if (file !=null&&!string.IsNullOrEmpty(file.FileName) && file.ContentLength <=5000000)
{
bool flag = ValidateFileAndGetName(type, file, id, out newFileName);
if (flag)
{
string filePath = APPLICATIONPATH + virtualPath +@"\"+ newFileName;
string sFilePath = APPLICATIONPATH + virtualPath +@"\s_"+ newFileName;
string middleFilePath = APPLICATIONPATH + virtualPath +@"\m_"+ newFileName;
string bigFilePath = APPLICATIONPATH + virtualPath +@"\big_"+ newFileName;
file.SaveAs(filePath);
if (type != UploadingFileType.Docuemnt)
MakeThumbnail(filePath, sFilePath,
214, 159, "HW");
MakeThumbnail(filePath, middleFilePath,
400, 300, "HW");
}
return flag;
}

returnfalse;
}
///<summary>
/// 文件存储
///</summary>
publicstaticbool UploadImageToServer(UploadingFileType type, HttpPostedFileBase file, string virtualPath, string id, int ImageWidth, int ImageHeight, outstring newFileName)
{
newFileName
=string.Empty;
if (file !=null&&!string.IsNullOrEmpty(file.FileName) && file.ContentLength <=5000000)
{
bool flag = ValidateFileAndGetName(type, file, id, out newFileName);
if (flag)
{
string filePath = APPLICATIONPATH + virtualPath +@"\"+ newFileName;
string sFilePath = APPLICATIONPATH + virtualPath +@"\s_"+ newFileName;
file.SaveAs(filePath);
if (type != UploadingFileType.Docuemnt)
MakeThumbnail(filePath, sFilePath, ImageWidth, ImageHeight,
"HW");
}
return flag;
}

returnfalse;
}
///<summary>
/// 验证上传文件是否合法并设置获取新的文件名
///</summary>
privatestaticbool ValidateFileAndGetName(UploadingFileType type, HttpPostedFileBase file, string id, outstring newFileName)
{
id
=string.IsNullOrEmpty(id) ? GetGuid() : id;
int index = file.FileName.LastIndexOf(".");
string suffix = file.FileName.Substring(index +1).Trim().ToLower();
newFileName
=string.Format("{0}.{1}", id, suffix);

switch (type)
{
case UploadingFileType.Docuemnt:
return FileIsValid(suffix, DocumentFileIsValid);
case UploadingFileType.Image:
return FileIsValid(suffix, ImageFileIsValid);
default:
returnfalse;
}
}
/// 生成缩略图
///</summary>
///<param name="originalImagePath">源图路径(物理路径)</param>
///<param name="thumbnailPath">缩略图路径(物理路径)</param>
///<param name="width">缩略图宽度</param>
///<param name="height">缩略图高度</param>
///<param name="mode">生成缩略图的方式</param>
publicstaticvoid MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System.Drawing.Image originalImage
= System.Drawing.Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;

int x =0;
int y =0;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case"HW"://指定高宽缩放(可能变形)
break;
case"W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case"H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case"Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh
= originalImage.Height;
ow
= originalImage.Height * towidth / toheight;
y
=0;
x
= (originalImage.Width - ow) /2;
}
else
{
ow
= originalImage.Width;
oh
= originalImage.Width * height / towidth;
x
=0;
y
= (originalImage.Height - oh) /2;
}
break;
default:
break;
}

//新建一个bmp图片
System.Drawing.Image bitmap =new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);

try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
#endregion

Controller.cs

View Code
引入:
using Project.Tools;
using System.Configuration;

privatestaticreadonlystring PRODUCTIMAGES = ConfigurationManager.AppSettings["PhotosImages"];//图片路径
///<summary>
/// 照片
///</summary>
///<returns></returns>
public ActionResult Photos()
{
ViewBag.PhotosImgUrl
="http://images.cnblogs.com/face-2.2.jpg";
return View();
}
///<summary>
/// 每周上传图片|图片编辑
///</summary>
///<returns></returns>
[HttpPost]
public ActionResult Photos(HttpPostedFileBase additionalImgFile)
{
ViewBag.PhotosImgUrl
="http://images.cnblogs.com/face-2.2.jpg";
#region 图片上传
bool flagUploadFile =true;
if (additionalImgFile !=null&&!string.IsNullOrEmpty(additionalImgFile.FileName))//修改图片
{
string imgUrl =string.Empty;
flagUploadFile
= Tool.UploadFileToServer(Tool.UploadingFileType.Image, additionalImgFile, PRODUCTIMAGES, "20110727", out imgUrl);
if (flagUploadFile)
{
ViewBag.PhotosImgUrl
= PRODUCTIMAGES +"s_"+ imgUrl;
}
else
{
Response.Write(
string.Format("<script type='text/javascript'>alert('上传图片失败!');history.go(-1);</script>"));
return View();
}
}
else
{
Response.Write(
string.Format("<script type='text/javascript'>alert('请选择要上传的照片!');history.go(-1);</script>"));
return View();
}
#endregion
return View();
}

页面.cshtml

View Code
<form action="UserSet" method="post" name="form1" enctype="multipart/form-data">

<img src="@ViewBag.UserHeadImgUrl" id="userHeadImgUrl" name="userHeadImgUrl" style="width:60px;height:60px;border:solid 1px #cccccc;" width="100px" height="100px"/>

<input name="additionalImgFile" type="file" size="20"/>

<input type="hidden" name="userHeadImgUrl" value="@ViewBag.UserHeadImgUrl"/><br />

<font color="#999999">图片格式必须为jpg或gif格式,图片大小不超过200K。</font>


</from> 

  

posted on 2011-08-22 15:46  落叶十九  阅读(79)  评论(0编辑  收藏  举报