
正文
webservice跨域上传图片
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
1.上传文件,在一般处理程序中处理
//1.接收post过来的文件
HttpPostedFile file = context.Request.Files[];
if (file.ContentLength > || file.ContentLength > )
{
if (file.ContentType.Contains("image/"))
{
//2.讲文件转换为文件流
Stream stream = file.InputStream;
//3.创建容纳文件流的byte数组
byte[] buff = new byte[stream.Length];
//4.将流存储进byte数组中
stream.Read(buff, , buff.Length);
//5.将byte数组转换为base64字符串
string strParam = Convert.ToBase64String(buff);
//6.调用webService方法,传入文件字符串
srImg.wsImgSoapClient cl = new srImg.wsImgSoapClient();
int result = cl.AddFile(strParam);
if (result == )
{
context.Response.Write("上传成功");
}
}
else
{
context.Response.Write("您上传的不是图片类型");
}
}
else
{
context.Response.Write("您上传的文件大小错误");
}
ashx后台处理上传文件
2.在webService方法中做如下处理:
#region 通过流保存图片文件
/// <summary>
/// 通过流保存图片文件
/// </summary>
/// <param name="streamStr">文件流字符串</param>
/// <returns></returns>
[WebMethod]
public int AddFile(string streamStr)
{
//1.将文件字符流转换为byte数组
byte[] imageBytes = Convert.FromBase64String(streamStr);
//2.根据数组获取存储区内存流
MemoryStream stream = new MemoryStream(imageBytes);
//3.根据file获取stream流,然后根据流生成image对象
using (Image img = Image.FromStream(stream))
{
//设置压缩率
double rate = ;
//开始压缩文件
return ThumImg(img, rate);
}
}
webservice
3.通用简单压缩方法,需要搜索更好的优化方法
#region 压缩文件
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="img">图片对象</param>
/// <param name="rate">压缩率</param>
/// <returns></returns>
public int ThumImg(Image img, double rate)
{
//1.创建新的压缩位图
using (Image thumImg = new Bitmap((int)(img.Width * rate), (int)(img.Height * rate)))
{
using (Graphics g = Graphics.FromImage(thumImg))
{
//2.在压缩图片按原图画出缩小版的图
g.DrawImage(img, new Rectangle(, , thumImg.Width, thumImg.Height), new Rectangle(, , img.Width, img.Height), GraphicsUnit.Pixel);
}
//3.存储图片文件
string phyPath = System.Web.HttpContext.Current.Server.MapPath("/upload/");
thumImg.Save(phyPath + Guid.NewGuid().ToString() + "." + GetImageFormat(thumImg), System.Drawing.Imaging.ImageFormat.Jpeg);
return ;
}
}
#endregion
图片压缩方法
4.通过image对象判断图片后缀方法
#region 返回图片格式(和文件名后缀无关)
/// <summary>
/// 返回图片格式(和文件名后缀无关)
/// </summary>
/// <param name="strImgPath">图片路径及名称</param>
/// <returns>jpeg\gif\bmp\png\tif\icon\wmf</returns>
string GetImageFormat(Image imgSrc)
{
string strImgFormat = "jpg";
if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
strImgFormat = "jpeg";
else if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
strImgFormat = "gif";
else if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
strImgFormat = "bmp";
else if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
strImgFormat = "png";
else if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
strImgFormat = "tiff";
else if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon))
strImgFormat = "icon";
else if (imgSrc.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Wmf))
strImgFormat = "wmf";
return strImgFormat;
}
#endregion
通过image对象判断后缀







