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

创建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[];
//获取图片的名称
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() + ImgExtention;
string serverPath = path + imgName;//文件保存位置及命名
string imgPath = subPath + imgName;
try
{
img.Save(serverPath);
return imgPath;
}
catch
{
return "";
}
} }
}

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

   
ImgUpLoad load = new ImgUpLoad();
string imgUrl = load.ImgUp(context);

最新文章

  1. 同上! 下拉复选框 点击当前的checkbox 选中后面li 添加到指定区域
  2. 人人都是 DBA(II)SQL Server 元数据
  3. Asp.net MVC验证哪些事(3)-- Remote验证及其改进(附源码)
  4. 转一篇简易易懂的android回调的实现---&gt;(转的)
  5. Redis学习笔记(1) Redis介绍及基础
  6. 通过PHP扩展phpredis操作redis
  7. C# mvc中为Controller或Action添加定制特性实现登录验证
  8. 修改镜像文件EI.CFG
  9. Xamarin iOS编写第一个应用程序创建工程
  10. C#基本线程同步
  11. memset memcpy函数
  12. 关于C/S框架网单表绑定,查询
  13. vue中路由按需加载的几种方式
  14. 设计模式六: 模板方法(Template Method)
  15. 18.Canny边缘检测
  16. mysql表理解
  17. Err.number错误号和可捕获的 Microsoft access 数据库引擎和 DAO错误说明
  18. python eric6 IDE
  19. 改变进程的优先级,nice,getpriority,setpriority
  20. Hibernate查询的六种方式

热门文章

  1. .net framework 4.0 安装一直失败,错误代码0x80240037,解决
  2. C++ 相关问题记录
  3. Python之数据处理-2
  4. C#-Parallel
  5. vue+iview的form表单校验总结
  6. 关于Git无法提交 index.lock的解决办法
  7. 【转载】IIS一个网站如何绑定多个主机域名
  8. fatfs源码阅读
  9. 基本代码、插值表达式、v-cloak
  10. DB2新建编目及删除编目