ashx 图片上传

 

为了方便多出调用图片上传方法       首先我们将图片上传方法抽离出来

创建ashx 一个新的方法

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web; namespace FileImg
{
/// <summary>
/// ImgUpLoad 的摘要说明
/// </summary>
public class ImgUpLoad : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
} public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 图片上传 并保存至服务器 返回 保存图片的相对路径URL
/// </summary>
/// <param name="context"></param>
/// <param name="file"></param>
/// <returns></returns>
public string ImgUp(HttpContext context)
{
//上传的第一个文件
HttpPostedFile file = context.Request.Files[0];
//获取图片的名称
string ImgName = file.FileName;
//获取图片的扩展名
string ImgExtention = System.IO.Path.GetExtension(ImgName);
//将图片流文件保存在 字节序列容器 中
Stream stream = file.InputStream;
//将图片流文件转换为Image图片对象
Image img = Image.FromStream(stream); //将图片保存在服务器上 //为了防止图片名称重复 我们使用随机数命名
Random ran = new Random((int)DateTime.Now.Ticks);
//图片保存的目录 按照日期进行保存
string subPath = "/imgUploads/" + DateTime.Now.ToString("yyyyMMdd") + "/"; // 20190928
//图片保存的目录的绝对路径
string path = context.Server.MapPath(subPath);
//当文件夹路径不存在时 创建文件夹
if (false == System.IO.Directory.Exists(path))
{
//创建pic文件夹
System.IO.Directory.CreateDirectory(path);
}
string imgName = ran.Next(99999) + ImgExtention;
string serverPath = path + imgName;//文件保存位置及命名
string imgPath = subPath + imgName;
try
{
img.Save(serverPath);
return imgPath;
}
catch
{
return "";
}
} }
}

在你所要用到的方法里面进行调用上面的图片上传方法   这里可以接收到图片上传方法返回的  已经上传的图片的相对路径

   

//取到传过来的图片流
HttpPostedFile file = context.Request.Files[0];
//创建一个新的文件 ImgUpLoad
ImgUpLoad load = new ImgUpLoad();
//图片返回值为新文件里的ImgUp方法
string imgUrl = load.ImgUp(context, file);

最新文章

  1. Windows下图文详解PHP三种运行方式(php_mod、cgi、fastcgi)
  2. coursera机器学习笔记-神经网络,初识篇
  3. 大数据——sparksql
  4. libcurl发起post请求时间延迟问题。except为空即可
  5. [转] 计算几何模板Orz
  6. free-jqGrid
  7. shell 中函数放回字符串问题
  8. 第 5 章 工厂方法模式【Factory Method Pattern】
  9. FCKeditor 插件开发 示例
  10. USACO Section 4.2 Drainage Ditches(最大流)
  11. SWT的TableVierer的使用二(数据排序)
  12. android在当前app该文件下创建一个文件夹
  13. clearfix:after 清除css浮动
  14. tensorflow安装过程-(windows环境下)---详解(摆平了很多坑!)
  15. Lintcode397 Longest Increasing Continuous Subsequence solution 题解
  16. Python字节数组【bytes/bytearray】
  17. 重启报错:Failed to open /dev/initctl: No such device or address
  18. window.open 和showModalDialog的返回值
  19. python两个 list 获取交集,并集,差集的方法
  20. java_19List 集合

热门文章

  1. 用Python写一个滑动验证码
  2. python 之网络并发(非阻塞IO模型)
  3. day46——特殊符号、标签分类、标签
  4. Bean管理学习笔记
  5. SWD下载k60
  6. 关于Eclipse导入maven项目报空指针异常
  7. Android 常用开源库总结(持续更新)
  8. Python——2x和3x的区别汇总
  9. c# System.Collections接口图
  10. Linux路由:CentOS6的多种玩法