C# 中实现ftp 图片上传功能(多快好省)

前言

此篇讲到的是图片上传功能,每个网站必定会有这样类似的功能,上传文件、上传图片等等。那么接下来,看看我们EF+uploadfile+ftp如何玩转上传图片吧

效果预览

具体实现

一个简单数据库 只有一个主键Id,一个身份证正面路径和一个身份证背面路径三个字段。

首先呢,我们把实体类新建好如下:

public class ImageModel:BaseEntity
 {
  /// <summary>
  /// 用户Id
  /// </summary>
  public int ID { get; set; }
  /// <summary>
  ///身份证正面相对路径
  /// </summary>
  public string IDProofFront { get; set; }
  /// <summary>
  ///身份证背面相对路径
  /// </summary>
  public string IDProofBack { get; set; }
 }

其中 我们将身份信息实体继承自BaseEntity,我们看看BaseEntity里面是什么东东,代码如下:

public abstract partial class BaseEntity
 {
  public override bool Equals(object obj)
  {
   return Equals(obj as BaseEntity);
  }
  private Type GetUnproxiedType()
  {
   return GetType();
  }
  public virtual bool Equals(BaseEntity other)
  {
   if (other == null)
    return false;
   if (ReferenceEquals(this, other))
    return true;
   return false;
  }
  public override int GetHashCode()
  {
   return base.GetHashCode();
  }
  public static bool operator ==(BaseEntity x, BaseEntity y)
  {
   return Equals(x, y);
  }
  public static bool operator !=(BaseEntity x, BaseEntity y)
  {
   return !(x == y);
  }
 }

这里,我们将BaseEntity定义成一个抽象类,里面包含一些静态方法和重载方法

======================回到HTML=======

我们先回过头来讲页面,上面演示的是一个很简单的单页面,HTML代码如下:

 <form enctype="multipart/form-data" id="form" action="/Home/UpLoadImage" method="post">
  <div class="full_w" style="margin-top: 100px; margin-left: 30%; width: 800px;">
   <div class="h_title">&nbsp;<b>用户上传的文件</b></div>
   <div class="entry">
    步骤: <span class="red" style="color: red">(上传资料必须是bmp,gif,jpg,jpeg,png类型,不能大于2M)</span>
    <ol>
     <li>先按『选择』键选择上传文件;</li>
     <li>按『上传』键上传文件;</li>
     <li>按『保存』键保存文件;</li>
    </ol>
   </div>
   <div class="entry">
    <div class="sep"></div>
   </div>
   <div class="entry">
    <div id="wrapper" style="text-align: center; position: relative;">
     <div class="form-group">
      <input id="uploadfile" type="file" value="浏览..." class="file" name="FileName" data-upload-url="#" style="position: absolute; top: 0; right: 0; min-width: 100%; min-height: 100%; text-align: right; opacity: 0; background: none repeat scroll 0 0 transparent; cursor: inherit; display: block;" />
     </div>
    </div>
   </div>
   <table>
    <tbody>
     <tr>
      <td class="entry">身份证正面</td>
      <td>
       @if (Model == null || Model.ID == null || string.IsNullOrEmpty(Model.IDProofFront))
       {
        <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" target="_blank" class="winView">
         <img style="border: none; width: 150px; height: 100px" src="/img/noupload.png" />
        </a>
       }
       else
       {
        <a href="@(ViewBag.pathSrc + Model.IDProofFront)" rel="external nofollow" target="_blank"class="winView" >
         <img style="border: none; width: 150px; height: 100px" src="@(ViewBag.pathSrc + Model.IDProofFront)" />
        </a>
       }
       @Html.HiddenFor(m => m.IDProofFront)
       @Html.HiddenFor(m => m.ID)
      </td>
      <td>
       <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton btnFinleUP" data-op="1" data-type="image">上传</a>
      </td>
     </tr>
     <tr>
      <td class="entry">身份证背面</td>
      <span id="lblinfosi" style="color: Green"></span>
      <td>
       @if (Model == null || Model.ID == null || string.IsNullOrEmpty(Model.IDProofBack))
       {
        <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" target="_blank" class="winView">
         <img style="border: none; width: 150px; height: 100px" src="/img/noupload.png" />
        </a>
       }
       else
       {
        <a href="@(ViewBag.pathSrc + Model.IDProofBack)" rel="external nofollow" target="_blank" class="winView" >
         <img style="border: none; width: 150px; height: 100px" src="@(ViewBag.pathSrc + Model.IDProofBack)" />
        </a>
       }
       @Html.HiddenFor(m => m.IDProofBack)
      </td>
      <td>
       <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton btnFinleUP" data-op="2" data-type="image">上传</a>
      </td>
     </tr>
    </tbody>
   </table>
   <div class="entry">
    <button class="button" name="btnSaveAll" value="保存" id="btnSaveAll" style="height: 30px; width: 80px; text-align: center;">保存</button>
    <a href="/Home/Index" rel="external nofollow" style="height: 30px; text-align: center; width: 80px; background: #ffffff; border: 1px solid #DCDCDC; border-radius: 2px; color: #444444; cursor: pointer; display: inline-block; font: 700 11px Tahoma, Arial, sans-serif; margin-right: 10px; padding: 7px 12px 7px 12px; position: relative; text-decoration: none; text-shadow: 0px 1px 0px #FFFFFF;">返回</a>
   </div>
  </div>
 </form>

现在我们看页面将会毫无样式,所以我们先引用下样式,这里引用了bootstrap 和一个 style2.css ,引入样式后 界面如下:

其中,关于选择框是用了一个js单独封装起来了,是代码中的zh.js,代码如下:

/*!
 * FileInput Chinese Translations
 *
 * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
 * any HTML markup tags in the messages must not be converted or translated.
 *
 * @see http://github.com/kartik-v/bootstrap-fileinput
 * @author kangqf <kangqingfei@gmail.com>
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
(function ($) {
 "use strict";
 $.fn.fileinputLocales['zh'] = {
  fileSingle: '文件',
  filePlural: '个文件',
  browseLabel: '选择 &hellip;',
  removeLabel: '移除',
  removeTitle: '清除选中文件',
  cancelLabel: '取消',
  cancelTitle: '取消进行中的上传',
  uploadLabel: '上传',
  uploadTitle: '上传选中文件',
  msgNo: '没有',
  msgNoFilesSelected: '',
  msgCancelled: '取消',
  msgZoomModalHeading: '详细预览',
  msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
  msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
  msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
  msgFileNotFound: '文件 "{name}" 未找到!',
  msgFileSecured: '安全限制,为了防止读取文件 "{name}".',
  msgFileNotReadable: '文件 "{name}" 不可读.',
  msgFilePreviewAborted: '取消 "{name}" 的预览.',
  msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
  msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
  msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
  msgFileTypes: {
   'image': 'image',
   'html': 'HTML',
   'text': 'text',
   'video': 'video',
   'audio': 'audio',
   'flash': 'flash',
   'pdf': 'PDF',
   'object': 'object'
  },
  msgUploadAborted: '该文件上传被中止',
  msgUploadThreshold: 'Processing...',
  msgUploadEmpty: 'No valid data available for upload.',
  msgValidationError: '验证错误',
  msgLoading: '加载第 {index} 文件 共 {files} &hellip;',
  msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
  msgSelected: '{n} {files} 选中',
  msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
  msgImageWidthSmall: '宽度的图像文件的"{name}"的必须是至少{size}像素.',
  msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
  msgImageWidthLarge: '宽度的图像文件"{name}"不能超过{size}像素.',
  msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
  msgImageResizeError: '无法获取的图像尺寸调整。',
  msgImageResizeException: '错误而调整图像大小。<pre>{errors}</pre>',
  msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  msgAjaxProgressError: '{operation} failed',
  ajaxOperations: {
   deleteThumb: 'file delete',
   uploadThumb: 'single file upload',
   uploadBatch: 'batch file upload',
   uploadExtra: 'form data upload'
  },
  dropZoneTitle: '拖拽文件到这里 &hellip;<br>支持多文件同时上传',
  dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)',
  fileActionSettings: {
   removeTitle: '删除文件',
   uploadTitle: '上传文件',
   zoomTitle: '查看详情',
   dragTitle: '移动 / 重置',
   indicatorNewTitle: '没有上传',
   indicatorSuccessTitle: '上传',
   indicatorErrorTitle: '上传错误',
   indicatorLoadingTitle: '上传 ...'
  },
  previewZoomButtonTitles: {
   prev: '预览上一个文件',
   next: '预览下一个文件',
   toggleheader: '缩放',
   fullscreen: '全屏',
   borderless: '无边界模式',
   close: '关闭当前预览'
  }
 };
})(window.jQuery);

好了,界面大概就整成这样子,现在需要我们实现功能了。首先用JS将上传控件初始化一下:

//上传控件初始化
 function initFileUpload() {
  $("#uploadfile").fileinput({
   //uploadExtraData: { kvId: '10' },
   language: 'zh', //设置语言 
   showUpload: false, //是否显示上传按钮
   uploadAsync: true, //默认异步上传
   showRemove: false,
   autoReplace: true,
   maxFileCount: 1,
   maxFileSize: 10240,
   dropZoneTitle: '拖拽文件到这里 &hellip;<br>仅限.pdf, .jpg, .jpeg, .gif',
   enctype: 'multipart/form-data',
   fileActionSettings: { uploadClass: "hidden", zoomClass: "hidden", removeClass: "hidden" },
   allowedFileExtensions: ['jpg', 'png', 'gif', 'pdf'],//接收的文件后缀
   msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
   uploadUrl: "/FileUpload/FileUpLoad", //上传的地址
  }).on("filebatchselected", function (event, files) {
   $(".file-preview-success").remove();
  })
  $("#uploadfile").on("fileuploaded", function (event, data, previewId, index) {
   console.log("accountData 初始化后 FileOpt" + accountData);
   console.log("accountData.FileOpt " + accountData.FileOpt);
   var obj = data.response;
   if (obj.Status != 500 && obj.Data != undefined) {
    var src = accountData.PathSrc + obj.Data.FileName;
    showName = obj.Data.FileName;
    //alert(showName);
    var pId = accountData.PId;
    var fileObj = undefined;
    var field = "";
    var isPdf = false;
    debugger;
    if (accountData.FileOpt == 1) {
     fileObj = $("#IDProofFront");
     //$("#PersonInfo_OldIDFile").val(obj.Data.FileName);
     field = "IDProofFront";
     fileObj.val(obj.Data.FileName);
    } else if (accountData.FileOpt == 2) {
     fileObj = $("#IDProofBack");
     field = "IDProofBack";
     $("#IDProofBack").val(showName);
     fileObj.val(obj.Data.FileName);
    }
    //fileObj = $("#IDProofFront");
    //$("#IDProofFront").val(obj.Data.FileName);
    //field = "IDProofFront";
    //fileObj.val(obj.Data.FileName);
    fileObj.prev().attr("href", src);
    src = isPdf == true ? "/Content/images/PDF.png" : src;
    fileObj.prev().find("img").attr("src", src);
   } else {
    console.error(obj.Data);
   }
  });
  $('#uploadfile').on('filesuccessremove', function (event, id) {
  });
  $('#uploadfile').on('fileerror', function (event, data, msg) {
  });
  //上传
  $(".btnFinleUP").click(function () {
   var fileName = $("#uploadfile").val();
   var obj = document.getElementById("uploadfile");
   var type = $(this).attr("data-op");
   //alert("当前点击的type是:" + type);
   var fileType = $(this).attr("data-type");
   var files = $("#uploadfile").fileinput("getFileStack");
   if (files.length == 0) {
    layer.msg('请选择要上传的文件', function () { });
    return;
   }
   var array = fileType.split(",");
   var selectType = files[0].type.toLowerCase();
   var falg = false;
   for (var i = 0; i < array.length; i++) {
    if (selectType.indexOf(array[i]) == -1) {
     falg = false;
    } else
     falg = true;
    if (falg)
     break;
   }
   if (!falg) {
    layer.msg('只能选择' + fileType + ' 类型的文件', function () { });
    return;
   }
   accountData.FileOpt = type;
   $("#uploadfile").fileinput("upload");
  });
 }

然后再 加载页面的时候调用这个初始化即可

 $(function () {
  initFileUpload();
})

FTP上传操作

注意,再initFileUpload方法中 上传了图片,会自动访问uploadUrl 这个url地址,存放图片,我们先看看这个action如何通过ftp上传指定服务器的。

FileUpLoad方法如下

/// <summary>
  /// 通过ftp上传指定服务器
  /// </summary>
  /// <returns></returns>
  public ActionResult FileUpLoad()
  {
   bool flag = false;
   string msg = string.Empty;
   int size = Convert.ToInt16(_fileSize) * 1024 * 1024;
   try
   {
    Dictionary<string, string> fileDict = new Dictionary<string, string>();
    for (int i = 0; i < Request.Files.Count; i++)
    {
     HttpPostedFileBase file = Request.Files[i];
     string extension = Path.GetExtension(file.FileName);
     string[] fileExtensions = _fileExtension.Split(';');
     if (fileExtensions.Any(o => o.Equals(extension, StringComparison.OrdinalIgnoreCase)))
     {
      if (file.ContentLength <= size)
      {
       string fileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), Path.GetFileName(file.FileName));
       if (file.ContentLength <= 10 * 1024 * 1024)
       {
        byte[] buffer = new byte[file.ContentLength];
        file.InputStream.Read(buffer, 0, file.ContentLength);
        flag = FileUpLoad(buffer, file.FileName, out fileName, out msg);
       }
       else//图片压缩有问题>>
       {
        var stream = ImageHelper.GetPicThumbnail(file.InputStream, 40);
        byte[] buffer = new byte[stream.Length];
        stream.Read(buffer, 0, (int)stream.Length);
        flag = FileUpLoad(buffer, file.FileName, out fileName, out msg);
       }
       fileDict.Add(Request.Files.AllKeys[i], fileName);
      }
      else
      {
       msg = string.Format("上传文件不能大于{0}M", _fileSize);
      }
     }
     else
     {
      msg = string.Format("上传的文件类型不正确");
     }
    }
    return Json(new { Result = "0", MSG = "" + msg, Data = fileDict });
   }
   catch (Exception ex)
   {
    return Json(new { Result = "0", MSG = "网络异常,请稍后再试" });
   }
  }

其中 _fileExtension _filePath _fileSize 是分别从配置文件中读取出来的如下:     

private static string _fileExtension = ConfigurationManager.AppSettings["FileType"];
  private readonly string _filePath = ConfigurationManager.AppSettings["UploadPath"];
  private readonly string _fileSize = ConfigurationManager.AppSettings["FileSizem"];

方法中有一个 FileUpLoad 上传文件的方法 如下:

/// <summary>
  /// 上传文件
  /// </summary>
  /// <param name="fileBytes"></param>
  /// <param name="originalName"></param>
  /// <param name="msg"></param>
  /// <returns></returns>
  protected bool FileUpLoad(byte[] fileBytes, string originalName, out string newFileName, out string msg)
  {
   msg = "";
   newFileName = "";
   try
   {
    FTPUpFile ftp = new FTPUpFile();
    newFileName = ftp.UpFile(fileBytes, originalName);
    if (string.IsNullOrEmpty(newFileName))
    {
     msg = "上传文件时出错!";
     return false;
    }
    return true;
   }
   catch (Exception ex)
   {
    msg = ex.Message;
    return false;
   }
  }

其中

FTPUpFile 是一个ftp上传文件帮助类,大家可以直接照搬 ,代码如下:

/// <summary>
 /// FTP上传文件
 /// </summary>
 public class FTPUpFile
 {
  string Filetype = ConfigurationManager.AppSettings["FileType"];
  string ipaddress = ConfigurationManager.AppSettings["IPaddress"];
  string Username = ConfigurationManager.AppSettings["UserName"];
  string Password = ConfigurationManager.AppSettings["Password"];
  /// <summary>
  /// FTP上传文件
  /// </summary>
  /// <param name="filename">上传文件路径</param>
  /// <param name="ftpServerIP">FTP服务器的IP和端口</param>
  /// <param name="ftpPath">FTP服务器下的哪个目录</param>
  /// <param name="ftpUserID">FTP用户名</param>
  /// <param name="ftpPassword">FTP密码</param>
  public bool Upload(string filename, string ftpServerIP, string ftpPath, string ftpUserID, string ftpPassword)
  {
   FileInfo fileInf = new FileInfo(filename);
   string uri = "ftp://" + ftpServerIP + "/" + ftpPath + "/" + fileInf.Name;
   try
   {
    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    // ftp用户名和密码
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    reqFTP.KeepAlive = false;
    // 指定执行什么命令
    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
    // 指定数据传输类型
    reqFTP.UseBinary = true;
    // 上传文件时通知服务器文件的大小
    reqFTP.ContentLength = fileInf.Length;
    //this.Invoke(InitUProgress, fileInf.Length);
    // 缓冲大小设置为2kb
    int buffLength = 4096;
    byte[] buff = new byte[buffLength];
    int contentLen;
    // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
    FileStream fs = fileInf.OpenRead();
    // 把上传的文件写入流
    Stream strm = reqFTP.GetRequestStream();
    contentLen = fs.Read(buff, 0, buffLength);
    while (contentLen != 0)
    {
     strm.Write(buff, 0, contentLen);
     contentLen = fs.Read(buff, 0, buffLength);
    }
    // 关闭两个流
    strm.Close();
    strm.Dispose();
    fs.Close();
    fs.Dispose();
    return true;
   }
   catch (Exception ex)
   {
    return false;
   }
  }
  /// <summary>
  /// 新建目录
  /// </summary>
  /// <param name="ftpPath"></param>
  /// <param name="dirName"></param>
  public void MakeDir(string ftpPath, string dirName, string username, string password)
  {
   try
   {
    //实例化FTP连接
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + dirName));
    // ftp用户名和密码
    request.Credentials = new NetworkCredential(username, password);
    // 默认为true,连接不会被关闭
    request.KeepAlive = false;
    //指定FTP操作类型为创建目录
    request.Method = WebRequestMethods.Ftp.MakeDirectory;
    //获取FTP服务器的响应
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    response.Close();
   }
   catch (Exception ex)
   {
    //Respons
   }
  }
  /// <summary>
  /// 删除指定文件
  /// </summary>
  /// <param name="ftpPath"></param>
  /// <param name="dirName"></param>
  /// <param name="username"></param>
  /// <param name="password"></param>
  public void DeleteFile(string ftpPath, string username, string password)
  {
   try
   {
    // string uri = "ftp://" + ftpServerIP + "/" + ftpPath + "/" + fileInf.Name;
    //ftpPath = "ftp://192.168.1.111:2005/2012-12-05/20121206O5CATICE.docx";
    //password = "111";
    //username = "yuanluluoli";
    //实例化FTP连接
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
    request.Method = WebRequestMethods.Ftp.DeleteFile;
    // ftp用户名和密码
    request.Credentials = new NetworkCredential(username, password);
    // 默认为true,连接不会被关闭
    request.KeepAlive = false;
    //获取FTP服务器的响应
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    response.Close();
   }
   catch (Exception ex)
   {
    //Respons
   }
  }
  /// <summary>
  /// 检查目录是否存在
  /// </summary>
  /// <param name="ftpPath">要检查的目录的路径</param>
  /// <param name="dirName">要检查的目录名</param>
  /// <returns>存在返回true,否则false</returns>
  public bool CheckDirectoryExist(string ftpPath, string dirName, string username, string password)
  {
   bool result = false;
   try
   {
    //实例化FTP连接
    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
    // ftp用户名和密码
    request.Credentials = new NetworkCredential(username, password);
    request.KeepAlive = false;
    //指定FTP操作类型为创建目录
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    //获取FTP服务器的响应
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
    StringBuilder str = new StringBuilder();
    string line = sr.ReadLine();
    while (line != null)
    {
     str.Append(line);
     str.Append("|");
     line = sr.ReadLine();
    }
    string[] datas = str.ToString().Split('|');
    for (int i = 0; i < datas.Length; i++)
    {
     if (datas[i].Contains("<DIR>"))
     {
      int index = datas[i].IndexOf("<DIR>");
      string name = datas[i].Substring(index + 5).Trim();
      if (name == dirName)
      {
       result = true;
       break;
      }
     }
    }
    sr.Close();
    sr.Dispose();
    response.Close();
   }
   catch (Exception)
   {
    return false;
   }
   return result;
  }
  /// <summary>
  /// 上传文件
  /// </summary>
  /// <param name="buffer">文件的Byte数组</param>
  /// <param name="originalName">文件原始名字(带后缀名)</param>
  /// <param name="perStr">新文件名的前缀</param>
  /// <returns></returns>
  public string UpFile(byte[] buffer, string originalName, string perStr = "")
  {
   if (buffer == null || buffer.Length <= 0 || string.IsNullOrEmpty(originalName))
    throw new ArgumentException("参数错误!");
   string filePathstr = string.Empty;
   string filepathsql = null;
   try
   {
    string pathstr = perStr + DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
    filePathstr = "~/File/" + pathstr + rodumlist + Path.GetExtension(originalName);
    //Stream sr = upfile.PostedFile.InputStream;
    //byte[] file = new byte[sr.Length];
    //sr.Read(file, 0, file.Length);
    StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filePathstr));
    sw.BaseStream.Write(buffer, 0, buffer.Length);
    sw.Flush(); sw.Close();
    // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
    bool check;
    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
    string uri = @"ftp://" + ipaddress + "/";
    //检查是否存在此目录文件夹
    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
    {
     //存在此文件夹就直接上传
     check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
    }
    else
    {
     MakeDir(uri, ftpPath, Username, Password);//创建
     check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
    }
    //成功就更新
    if (check)
    {
     filepathsql = ftpPath + "/" + pathstr + rodumlist + Path.GetExtension(originalName);
    }
    //检查是否存在此文件
    if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
    {
     File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
    }
    return filepathsql;
   }
   catch (Exception ex)
   {
    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
    throw ex;
   }
  }
  /// <summary>
  /// 上传文件
  /// 不修改名字及后缀名
  /// </summary>
  /// <param name="originalFilePath">上传文件的绝对路径</param>
  /// <returns></returns>
  public string UpFile(string originalFilePath)
  {
   if (string.IsNullOrEmpty(originalFilePath))
    throw new ArgumentException("参数错误!");
   string filepathsql = null;
   try
   {
    //检查是否存在此文件
    if (!File.Exists(originalFilePath))
     throw new Exception("文件不存在!");
    //Stream sr = upfile.PostedFile.InputStream;
    //byte[] file = new byte[sr.Length];
    //sr.Read(file, 0, file.Length);
    // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
    bool check;
    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
    string uri = @"ftp://" + ipaddress + "/";
    //检查是否存在此目录文件夹
    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
    {
     //存在此文件夹就直接上传
     check = Upload(originalFilePath, ipaddress, ftpPath, Username, Password);
    }
    else
    {
     MakeDir(uri, ftpPath, Username, Password);//创建
     check = Upload(originalFilePath, ipaddress, ftpPath, Username, Password);
    }
    //成功就更新
    if (check)
    {
     filepathsql = ftpPath + "/" + Path.GetFileName(originalFilePath);
    }
    //检查是否存在此文件
    if (File.Exists(originalFilePath))
    {
     File.Delete(originalFilePath);
    }
    return filepathsql;
   }
   catch (Exception ex)
   {
    //File.Delete(originalFilePath);
    throw ex;
   }
  }
  public string Ftp_Up(HtmlInputFile upfile)
  {
   //Encrypt En = new Encrypt();
   string filePathstr = string.Empty;
   string filepathsql = null;
   try
   {
    string pathstr = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
    filePathstr = "~/File/" + pathstr + rodumlist + Path.GetExtension(upfile.PostedFile.FileName);
    Stream sr = upfile.PostedFile.InputStream;
    byte[] file = new byte[sr.Length];
    sr.Read(file, 0, file.Length);
    StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filePathstr));
    sw.BaseStream.Write(file, 0, file.Length);
    sw.Flush(); sw.Close(); sr.Flush(); sr.Close();
    // file.SaveAs(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
    bool check;
    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
    string uri = @"ftp://" + ipaddress + "/";
    //检查是否存在此目录文件夹
    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
    {
     //存在此文件夹就直接上传
     check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
    }
    else
    {
     MakeDir(uri, ftpPath, Username, Password);//创建
     check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
    }
    //成功就更新
    if (check)
    {
     filepathsql = ftpPath + "/" + pathstr + rodumlist + Path.GetExtension(upfile.PostedFile.FileName);
    }
    //检查是否存在此文件
    if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
    {
     File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
    }
    return filepathsql;
   }
   catch (Exception)
   {
    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
    return filepathsql;
    // Response.Write("<script>alert(" + ex.Message + ");</script>");
   }
  }
  /// <summary>
  /// 上传
  /// </summary>
  /// <param name="file"></param>
  /// <returns></returns>
  public string Ftp_Up(HttpPostedFileBase postedFile)
  {
   string filePathstr = string.Empty;
   string filepathsql = null;
   try
   {
    string pathstr = DateTime.Now.ToString("yyyyMMddHHmmss");
    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
    string filename = System.IO.Path.GetFileName(postedFile.FileName);
    string eExtension = Path.GetExtension(filename);
    string strLocation = HttpContext.Current.Server.MapPath("~/File/");
    filePathstr = strLocation + pathstr + rodumlist + eExtension;
    postedFile.SaveAs(filePathstr);
    bool check;
    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
    string uri = @"ftp://" + ipaddress + "/";
    //检查是否存在此目录文件夹
    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
    {
     //存在此文件夹就直接上传
     check = Upload(filePathstr, ipaddress, ftpPath, Username, Password);
    }
    else
    {
     MakeDir(uri, ftpPath, Username, Password);//创建
     check = Upload(filePathstr, ipaddress, ftpPath, Username, Password);
    }
    //成功就更新
    if (check)
    {
     filepathsql = ftpPath + "/" + pathstr + rodumlist + eExtension;
    }
    //检查是否存在此文件
    if (File.Exists(filePathstr))
    {
     File.Delete(filePathstr);
    }
    return filepathsql;
   }
   catch (Exception ex)
   {
    //检查是否存在此文件
    if (File.Exists(filePathstr))
    {
     File.Delete(filePathstr);
    }
    return "";
    // Response.Write("<script>alert(" + ex.Message + ");</script>");
   }
  }
  /// <summary>
  /// FTP下载文件在服务器目录
  /// </summary>
  /// <param name="pathname">本地保存目录路径和文件名称</param>
  /// <param name="filename">FTP目录路径和文件名称</param>
  /// <returns></returns>
  public bool FileDown(string pathname, string filename)
  {
   string uri = "ftp://" + ipaddress + "/" + filename;
   string FileName = pathname;//本地保存目录
   //创建一个文件流
   FileStream fs = null;
   Stream responseStream = null;
   try
   {
    //创建一个与FTP服务器联系的FtpWebRequest对象
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(uri));
    //连接登录FTP服务器
    request.Credentials = new NetworkCredential(Username, Password);
    request.KeepAlive = false;
    //设置请求的方法是FTP文件下载
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    //获取一个请求响应对象
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    //获取请求的响应流
    responseStream = response.GetResponseStream();
    //判断本地文件是否存在,如果存在,则打开和重写本地文件
    if (File.Exists(FileName))
     fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
    //判断本地文件是否存在,如果不存在,则创建本地文件
    else
    {
     fs = File.Create(FileName);
    }
    if (fs != null)
    {
     int buffer_count = 65536;
     byte[] buffer = new byte[buffer_count];
     int size = 0;
     while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
     {
      fs.Write(buffer, 0, size);
     }
     fs.Flush();
     fs.Close();
     responseStream.Close();
    }
    return true;
   }
   catch (Exception ex)
   {
    return false;
   }
   finally
   {
    if (fs != null)
     fs.Close();
    if (responseStream != null)
     responseStream.Close();
   }
  }
  /// <summary>
  /// 保存和上传图片
  /// </summary>
  /// <param name="imgtwo">需要上传图片</param>
  /// <param name="date"></param>
  /// <returns>文件路径</returns>
  public string SaveUploadImg(Bitmap imgtwo)
  {
   string filePathstr = string.Empty;
   string filepathsql = null;
   try
   {
    string pathstr = DateTime.Now.ToString().Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "");
    string rodumlist = GeneralHelper.GetMixPwd(10);//10位随机数
    filePathstr = "~/File/" + pathstr + rodumlist + ".jpg";
    imgtwo.Save(HttpContext.Current.Server.MapPath(filePathstr));//把文件上传到服务器的绝对路径上
    bool check;
    string ftpPath = DateTime.Now.ToString("yyyy-MM-dd");
    string uri = @"ftp://" + ipaddress + "/";
    //检查是否存在此目录文件夹
    if (CheckDirectoryExist(uri, ftpPath, Username, Password))
    {
     //存在此文件夹就直接上传
     check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
    }
    else
    {
     MakeDir(uri, ftpPath, Username, Password);//创建
     check = Upload(HttpContext.Current.Server.MapPath(filePathstr), ipaddress, ftpPath, Username, Password);
    }
    //成功就更新
    if (check)
    {
     filepathsql = ftpPath + "/" + pathstr + rodumlist + ".jpg";
    }
    //检查是否存在此文件
    if (File.Exists(HttpContext.Current.Server.MapPath(filePathstr)))
    {
     File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
    }
    imgtwo.Dispose();
    return filepathsql;
   }
   catch (Exception ex)
   {
    File.Delete(HttpContext.Current.Server.MapPath(filePathstr));
    return filepathsql;
   }
  }
  #region
  /// <summary>
  /// 文件大小
  /// </summary>
  public bool _File_Length(int ContentLength)
  {
   bool length = false;
   int FileLen = ContentLength;
   if (FileLen > 2048 * 1024 == false)//不能超过2M
   {
    length = true;
   }
   return length;
  }
  #endregion
  //用来获取文件类型
  public bool File_PastFileName(string fileName)
  {
   //bmp, doc, docx, gif, jpg, jpeg, pdf, png, tif, tiff
   bool isnot = true;
   string ext = Path.GetExtension(fileName);
   string[] type = Filetype.Split(';');
   for (int i = 0; i < type.Length; i++)
   {
    if (type[i].ToLower() == ext.ToLower())
    {
     isnot = false;
     break;
    }
   }
   return isnot;
  }
 }

值得注意的是:帮助类中也从配置文件中读取了存放地址、文件类型、用户名、密码等必要信息。这个大家可以自己再配置文件中配置,配置好了如下所示:

 <add key="FileSizem" value="10"></add>
 <add key="FileType" value=".bmp;.gif;.jpg;.jpeg;.png;.pdf" />
 <!---本地测试-->
 <add key="IPaddress" value="路径" />
 <!--FTP上传文件的帐号-->
 <add key="UserName" value="账号" />
 <!--FTP上传文件的密码-->
 <add key="Password" value="密码" />
 <!--后台显示图片地址-->
 <add key="PathSrc" value="路径" />

还有一个类是图片帮助类,代码如下:

public class ImageHelper
 {
  /// <summary>
  /// 图片压缩
  /// </summary>
  /// <param name="sFile">原图路径</param>
  /// <param name="dFile">保存路径</param>
  /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param>
  /// <param name="dWidth">宽度</param>
  /// <param name="dHeight">高度</param>
  /// <returns></returns>
  public static bool SavePicThumbnail(string sFile, string dFile, int flag, int dWidth = 0, int dHeight = 0)
  {

   System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
   return SavePicThumbnail(dFile, flag, iSource, dWidth, dHeight);


  }
  /// <summary>
  /// 图片压缩
  /// </summary>
  /// <param name="sFile">原图流</param>
  /// <param name="dFile">保存路径</param>
  /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param>
  /// <param name="dWidth">宽度</param>
  /// <param name="dHeight">高度</param>
  /// <returns></returns>
  public static bool SavePicThumbnail(Stream stream, string dFile, int flag, int dWidth = 0, int dHeight = 0)
  {

   System.Drawing.Image iSource = System.Drawing.Image.FromStream(stream);
   return SavePicThumbnail(dFile, flag, iSource, dWidth, dHeight);

  }



  #region GetPicThumbnail

  public static Stream GetPicThumbnail(Stream stream ,int flag, int dWidth = 0, int dHeight = 0)
  {
   System.Drawing.Image iSource = System.Drawing.Image.FromStream(stream);
   ImageFormat tFormat = iSource.RawFormat;
   int sW = 0, sH = 0;
   if (dHeight == 0 && dWidth == 0)
   {
    sW = iSource.Width;
    sH = iSource.Height;
   }
   else if (dWidth != 0)
   {
    sW = dWidth;
    sH = iSource.Height * dWidth / iSource.Width;
   }
   else if (dHeight != 0)
   {
    sH = dHeight;
    sW = iSource.Width * dHeight / iSource.Height;
   }
   Bitmap ob = new Bitmap(sW, sH);
   Graphics g = Graphics.FromImage(ob);
   g.Clear(Color.WhiteSmoke);
   g.CompositingQuality = CompositingQuality.HighQuality;
   g.SmoothingMode = SmoothingMode.HighQuality;
   g.InterpolationMode = InterpolationMode.HighQualityBicubic;
   g.DrawImage(iSource, new Rectangle(0, 0, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
   g.Dispose();
   //以下代码为保存图片时,设置压缩质量
   EncoderParameters ep = new EncoderParameters();
   long[] qy = new long[1];
   qy[0] = flag;//设置压缩的比例1-100
   EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
   ep.Param[0] = eParam;
   MemoryStream ms = new MemoryStream(); 
   try
   {
    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
    ImageCodecInfo jpegICIinfo = null;
    for (int x = 0; x < arrayICI.Length; x++)
    {
     if (arrayICI[x].FormatDescription.Equals("JPEG"))
     {
      jpegICIinfo = arrayICI[x];
      break;
     }
    }
    if (jpegICIinfo != null)
    {
     ob.Save(ms, jpegICIinfo, ep);//dFile是压缩后的新路径

    }
    else
    {
     ob.Save(ms, tFormat);
    }
    
    return stream;
   }
   catch
   {
    return null;
   }
   finally
   {
    iSource.Dispose();
    ob.Dispose();
   }
  }


  public static bool SavePicThumbnail(string dFile, int flag, System.Drawing.Image iSource, int dWidth = 0, int dHeight = 0)
  {

   ImageFormat tFormat = iSource.RawFormat;
   int sW = 0, sH = 0;
   if (dHeight == 0 && dWidth == 0)
   {
    sW = iSource.Width;
    sH = iSource.Height;
   }
   else if (dWidth != 0)
   {
    sW = dWidth;
    sH = iSource.Height * dWidth / iSource.Width;
   }
   else if (dHeight != 0)
   {
    sH = dHeight;
    sW = iSource.Width * dHeight / iSource.Height;
   }
   Bitmap ob = new Bitmap(sW, sH);
   Graphics g = Graphics.FromImage(ob);
   g.Clear(Color.WhiteSmoke);
   g.CompositingQuality = CompositingQuality.HighQuality;
   g.SmoothingMode = SmoothingMode.HighQuality;
   g.InterpolationMode = InterpolationMode.HighQualityBicubic;
   g.DrawImage(iSource, new Rectangle(0, 0, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
   g.Dispose();
   //以下代码为保存图片时,设置压缩质量
   EncoderParameters ep = new EncoderParameters();
   long[] qy = new long[1];
   qy[0] = flag;//设置压缩的比例1-100
   EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
   ep.Param[0] = eParam;
   try
   {
    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
    ImageCodecInfo jpegICIinfo = null;
    for (int x = 0; x < arrayICI.Length; x++)
    {
     if (arrayICI[x].FormatDescription.Equals("JPEG"))
     {
      jpegICIinfo = arrayICI[x];
      break;
     }
    }
    if (jpegICIinfo != null)
    {
     ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
    }
    else
    {
     ob.Save(dFile, tFormat);
    }
    return true;
   }
   catch
   {
    return false;
   }
   finally
   {
    iSource.Dispose();
    ob.Dispose();
   }
  }
  #endregion
 }

然后我们通过在fileuploaded的回调函数中绑定url即可显示上传后的图片,效果如下图:

不过这个只是上传到ftp服务器上了,并没有保存到数据库,现在我们要做的就是通过EF的方式将上传的图片保存到数据库。

保存图片

首先我们要建一个操作的接口基类,并且还要约束成BaseEntity,代码如下

public interface IRepository<T> where T : BaseEntity
 {
  /// <summary>
  /// 根据过滤条件,获取记录
  /// </summary>
  /// <param name="exp"></param>
  /// <param name="isNoTracking">(默认不跟踪实体状态)使用NoTracking的查询会在性能方面得到改善</param>
  /// <returns></returns>
  IQueryable<T> Find(Expression<Func<T, bool>> exp = null, bool isNoTracking = true);
  /// <summary>
  /// 根据过滤条件,获取记录
  /// </summary>
  /// <param name="whereLambda"></param>
  /// <param name="isNoTracking">(默认不跟踪实体状态)使用NoTracking的查询会在性能方面得到改善</param>
  /// <param name="values"></param>
  /// <returns></returns>
  IQueryable<T> Find(string whereLambda = null, bool isNoTracking = true, params object[] values);
  IQueryable<TEntity> OtherTable<TEntity>() where TEntity : BaseEntity;
  IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
  /// <summary>
  /// 判断记录是否存在
  /// </summary>
  /// <param name="exp"></param>
  /// <returns></returns>
  bool IsExist(Expression<Func<T, bool>> exp);
  /// <summary>
  /// 查找单个(如果没找到则返回为NULL)
  /// </summary>
  /// <param name="exp"></param>
  /// <param name="isNoTracking">(默认不跟踪实体状态)使用NoTracking的查询会在性能方面得到改善</param>
  /// <returns></returns>
  T FindSingle(Expression<Func<T, bool>> exp, bool isNoTracking = true);
  /// <summary>
  /// 得到分页记录
  /// </summary>
  /// <param name="pageIndex">The pageindex.</param>
  /// <param name="pageSize">The pagesize.</param>
  /// <param name="total">总条数</param>
  /// <param name="exp">条件谓词</param>
  /// <param name="orderBy">排序,格式如:"Id"/"Id descending"</param>
  IQueryable<T> Find(int pageIndex, int pageSize, out int total, Expression<Func<T, bool>> exp = null, string orderBy = "");
  /// <summary>
  /// 得到分页记录
  /// </summary>
  /// <param name="pageIndex">The pageindex.</param>
  /// <param name="pageSize">The pagesize.</param>
  /// <param name="total">总条数</param>
  /// <param name="whereLambda">条件谓词</param>
  /// <param name="orderBy">排序,格式如:"Id"/"Id descending"</param>
  IQueryable<T> Find(int pageIndex, int pageSize, out int total, string whereLambda = "", string orderBy = "", params object[] values);
  /// <summary>
  /// 根据过滤条件获取记录数
  /// </summary>
  int GetCount(Expression<Func<T, bool>> exp = null);
  /// <summary>
  /// 添加实体
  /// </summary>
  /// <param name="entity">The entities.</param>
  /// <param name="isComit">是否提交(true)</param>
  /// <returns></returns>
  int Add(T entity, bool isComit = true);
  /// <summary>
  /// 批量添加
  /// </summary>
  /// <param name="entity">The entities.</param>
  /// <param name="isComit">是否提交(true)</param>
  int Adds(List<T> entitis, bool isComit = true);
  /// <summary>
  /// 更新实体(会更新实体的所有属性)
  /// </summary>
  /// <param name="entity">The entities.</param>
  /// <param name="isComit">是否提交(true)</param>
  /// <returns></returns>
  int Update(T entity, bool isComit = true);
  /// <summary>
  /// 删除实体
  /// </summary>
  /// <param name="entity">The entities.</param>
  /// <param name="isComit">是否提交(true)</param>
  /// <returns></returns>
  int Delete(T entity, bool isComit = true);
  /// <summary>
  /// 实现按需要只更新部分更新
  /// <para>如:Update(u =>u.Id==1,u =>new User{Name="ok"});</para>
  /// </summary>
  /// <param name="where">The where.</param>
  /// <param name="entity">The entity.</param>
  int Update(Expression<Func<T, bool>> where, Expression<Func<T, T>> entity);
  /// <summary>
  /// 批量按条件删除
  /// </summary>
  /// <param name="exp"></param>
  int Delete(Expression<Func<T, bool>> exp);
  /// <summary>
  /// 对数据库执行给定的 DDL/DML 命令。
  /// </summary>
  /// <param name="sql">sql</param>
  /// <param name="parameters">参数</param>
  /// <returns></returns>
  int ExecuteSqlCommand(string sql, params SqlParameter[] parameters);
  /// <summary>
  /// 执行SQL查询语句
  /// </summary>
  /// <param name="sql"></param>
  /// <returns></returns>
  DbRawSqlQuery<int> ExecuteSqlQuery(string sql);
  /// <summary>
  /// 执行原始的sql查询
  /// </summary>
  /// <typeparam name="TElement">返回的泛型类型</typeparam>
  /// <param name="sql">sql</param>
  /// <param name="parameters">参数</param>
  /// <returns></returns>
  IList<TElement> SqlQuery<TElement>(string sql, params SqlParameter[] parameters);
  /// <summary>
  /// 开启一个事务
  /// </summary>
  /// <param name="fun"></param>
  bool BeginTransaction(Func<bool> fun);
  /// <summary>
  /// 执行SQL语句或存储过程
  /// 返回Datatable数据集
  /// </summary>
  /// <param name="sql">SQL语句或存储过程 例如:exec usp_procedure</param>
  /// <param name="parameters">参数列表</param>
  /// <returns></returns>
  DataTable SqlQueryForDataTable(string sql, DbParameter[] parameters);
  /// <summary>
  /// 返回Datatable数据集
  /// </summary>
  /// <param name="proName">存储过程名</param>
  /// <param name="parameters">参数列表</param>
  /// <returns></returns>
  [Obsolete("此方法已过时,请改用SqlQueryForDataTable")]
  DataTable ExecuteForDataTable(string proName, IDataParameter[] parameters);
 }

然后需要实现这个基类接口,代码如下:

public class BaseRepository<T> : IRepository<T> where T : BaseEntity
  {
    private DbContext Context
    {
      get
      {
        DbContext db = (DbContext)CallContext.GetData("DbContext");
        if (db == null)
        {
          db = new DbContext();
          // db.Database.Log = o => LoggingHelper.Instance.Logging(LogLevel.Debug, o);
          CallContext.SetData("DbContext", db);
        }
        return db;
      }
    }
    /// <summary>
    /// 根据过滤条件,获取记录
    /// </summary>
    /// <param name="exp"></param>
    /// <param name="isNoTracking">(默认不跟踪实体状态)使用NoTracking的查询会在性能方面得到改善</param>
    /// <returns></returns>
    public IQueryable<T> Find(Expression<Func<T, bool>> exp = null, bool isNoTracking = true)
    {
      return Filter(exp, isNoTracking);
    }
    /// <summary>
    /// 根据过滤条件,获取记录
    /// </summary>
    /// <param name="whereLambda"></param>
    /// <param name="isNoTracking">(默认不跟踪实体状态)使用NoTracking的查询会在性能方面得到改善</param>
    /// <param name="values"></param>
    /// <returns></returns>
    public IQueryable<T> Find(string whereLambda = null, bool isNoTracking = true, params object[] values)
    {
      return Filter(whereLambda, isNoTracking, values);
    }
    /// <summary>
    /// 判断记录是否存在
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public bool IsExist(Expression<Func<T, bool>> exp)
    {
      return Context.Set<T>().Any(exp);
    }
    /// <summary>
    /// 查找单个(如果没找到则返回为NULL)
    /// </summary>
    /// <param name="exp"></param>
    /// <param name="isNoTracking">(默认不跟踪实体状态)使用NoTracking的查询会在性能方面得到改善</param>
    /// <returns></returns>
    public T FindSingle(Expression<Func<T, bool>> exp, bool isNoTracking = true)
    {
      return Filter(exp, isNoTracking).FirstOrDefault();
    }
    /// <summary>
    /// 得到分页记录
    /// </summary>
    /// <param name="pageIndex">The pageindex.</param>
    /// <param name="pageSize">The pagesize.</param>
    /// <param name="total">总条数</param>
    /// <param name="exp">条件谓词</param>
    /// <param name="orderBy">排序,格式如:"Id"/"Id descending"</param>
    public IQueryable<T> Find(int pageIndex, int pageSize, out int total, Expression<Func<T, bool>> exp = null, string orderBy = "")
    {
      if (pageIndex < 1) pageIndex = 1;
      var query = Filter(exp);
      if (!string.IsNullOrEmpty(orderBy))
        query = query.OrderBy(orderBy);
      total = query.Count();
      ///return query.Skip(pageSize * (pageIndex - 1)).Take(pageSize);
      return null;
    }
    /// <summary>
    /// 得到分页记录
    /// </summary>
    /// <param name="pageIndex">The pageindex.</param>
    /// <param name="pageSize">The pagesize.</param>
    /// <param name="total">总条数</param>
    /// <param name="whereLambda">条件谓词</param>
    /// <param name="orderBy">排序,格式如:"Id"/"Id descending"</param>
    public IQueryable<T> Find(int pageIndex, int pageSize, out int total, string whereLambda = "", string orderBy = "", params object[] values)
    {
      if (pageIndex < 1) pageIndex = 1;
      var query = Filter(whereLambda);
      if (string.IsNullOrEmpty(orderBy))
        query = query.OrderBy(orderBy);
      total = query.Count();
      // return query.Skip(pageSize * (pageIndex - 1)).Take(pageSize);
      return null;
    }
    /// <summary>
    /// 根据过滤条件获取记录数
    /// </summary>
    public int GetCount(Expression<Func<T, bool>> exp = null)
    {
      return Filter(exp).Count();
    }
    /// <summary>
    /// 添加书体
    /// </summary>
    /// <param name="entity">The entities.</param>
    /// <param name="isComit">是否提交(true)</param>
    /// <returns></returns>
    public int Add(T entity, bool isComit = true)
    {
      Context.Entry<T>(entity).State = System.Data.Entity.EntityState.Added;
      return isComit ? Context.SaveChanges() : 0;
    }
    /// <summary>
    /// 批量添加
    /// </summary>
    /// <param name="entity">The entities.</param>
    /// <param name="isComit">是否提交(true)</param>
    public int Adds(List<T> entitis, bool isComit = true)
    {
      foreach (T item in entitis)
      {
        Context.Entry<T>(item).State = System.Data.Entity.EntityState.Added;
      }
      return isComit ? Context.SaveChanges() : 0;
    }
    /// <summary>
    /// 更新实体(会更新实体的所有属性)
    /// </summary>
    /// <param name="entity">The entities.</param>
    /// <param name="isComit">是否提交(true)</param>
    /// <returns></returns>
    public int Update(T entity, bool isComit = true)
    {
      Context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
      return isComit ? Context.SaveChanges() : 0;
    }
    /// <summary>
    /// 删除实体
    /// </summary>
    /// <param name="entity">The entities.</param>
    /// <param name="isComit">是否提交(true)</param>
    /// <returns></returns>
    public int Delete(T entity, bool isComit = true)
    {
      Context.Set<T>().Remove(entity);
      return isComit ? Context.SaveChanges() : 0;
    }
    /// <summary>
    /// 实现按需要只更新部分更新
    /// <para>如:Update(u =>u.Id==1,u =>new User{Name="ok"});</para>
    /// </summary>
    /// <param name="where">The where.</param>
    /// <param name="entity">The entity.</param>
    public int Update(Expression<Func<T, bool>> where, Expression<Func<T, T>> entity)
    {
      return Context.Set<T>().Where(where).Update(entity);
    }
    /// <summary>
    /// 批量按条件删除
    /// </summary>
    /// <param name="exp"></param>
    public int Delete(Expression<Func<T, bool>> exp)
    {
      return Context.Set<T>().Where(exp).Delete();
    }
    /// <summary>
    /// 对数据库执行给定的 DDL/DML 命令。
    /// </summary>
    /// <param name="sql">sql</param>
    /// <param name="parameters">参数</param>
    /// <returns></returns>
    public int ExecuteSqlCommand(string sql, params SqlParameter[] parameters)
    {
      return Context.Database.ExecuteSqlCommand(sql, parameters);
    }
    /// <summary>
    /// 执行原始的sql查询
    /// </summary>
    /// <typeparam name="TElement">返回的泛型类型</typeparam>
    /// <param name="sql">sql</param>
    /// <param name="parameters">参数</param>
    /// <returns></returns>
    public IList<TElement> SqlQuery<TElement>(string sql, params SqlParameter[] parameters)
    {
      return Context.Database.SqlQuery<TElement>(sql, parameters).ToList();
    }
    public bool BeginTransaction(Func<bool> fun)
    {
      using (var trans = Context.Database.BeginTransaction())
      {
        try
        {
          var result = fun();
          trans.Commit();
          return result;
        }
        catch (Exception)
        {
          trans.Rollback();
          return false;
        }
      }
    }
    private IQueryable<T> Filter(Expression<Func<T, bool>> exp = null, bool isNoTracking = true)
    {
      var dbSet = Context.Set<T>().AsQueryable();
      if (exp != null)
        dbSet = dbSet.Where(exp);
      if (isNoTracking)
        dbSet = dbSet.AsNoTracking();
      return dbSet;
    }
    private IQueryable<T> Filter(string whereLambda = null, bool isNoTracking = true, params object[] values)
    {
      var dbSet = Context.Set<T>().AsQueryable();
      if (whereLambda != null)
        dbSet = dbSet.Where(whereLambda, values);
      if (isNoTracking)
        dbSet = dbSet.AsNoTracking();
      return dbSet;
    }
    public IQueryable<T> Table
    {
      get
      {
        return Find(whereLambda: null);
      }
    }
    public IQueryable<TEntity> OtherTable<TEntity>() where TEntity : BaseEntity
    {
      return Context.Set<TEntity>().AsNoTracking().AsQueryable();
    }
    public IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
    {
      return Context.Set<TEntity>();
    }
    /// <summary>
    /// 执行SQL查询语句
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public DbRawSqlQuery<int> ExecuteSqlQuery(string sql)
    {
      try
      {
        return Context.Database.SqlQuery<int>(sql);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
    /// <summary>
    /// 执行SQL语句或存储过程
    /// 返回Datatable数据集
    /// </summary>
    /// <param name="sql">SQL语句或存储过程 例如:exec usp_procedure</param>
    /// <param name="parameters">参数列表</param>
    /// <returns></returns>
    public System.Data.DataTable SqlQueryForDataTable(string sql, params System.Data.Common.DbParameter[] parameters)
    {
      SqlConnection conn = new System.Data.SqlClient.SqlConnection();
      try
      {
        conn = (SqlConnection)Context.Database.Connection;
        if (conn.State != ConnectionState.Open)
        {
          conn.Open();
        }
        SqlCommand cmd = new SqlCommand();
        StringBuilder sb = new StringBuilder(sql);
        if (parameters != null && parameters.Length > 0)
        {
          if (sql.StartsWith("exec ", StringComparison.OrdinalIgnoreCase))
            sb.AppendFormat(" {0}", string.Join(",", parameters.Select(o => o.ParameterName).ToArray()));
          foreach (var item in parameters)
          {
            cmd.Parameters.Add(item);
          }
        }
        cmd.Connection = conn;
        cmd.CommandText = sb.ToString();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable table = new DataTable();
        adapter.Fill(table);
        conn.Close();//连接需要关闭
        return table;
      }
      catch (Exception ex)
      {
        throw ex;
      }
      finally
      {
        if (conn.State == ConnectionState.Open)
          conn.Close();
      }
    }
    /// <summary>
    /// 返回Datatable数据集
    /// </summary>
    /// <param name="proName">存储过程名</param>
    /// <param name="parameters">参数列表</param>
    /// <returns></returns>
    [Obsolete("此方法已过时,请改用SqlQueryForDataTable")]
    public System.Data.DataTable ExecuteForDataTable(string proName, IDataParameter[] parameters)
    {
      try
      {
        SqlConnection conn = new System.Data.SqlClient.SqlConnection();
        conn.ConnectionString = Context.Database.Connection.ConnectionString;
        if (conn.State != ConnectionState.Open)
        {
          conn.Open();
        }
        SqlCommand cmd = new SqlCommand(proName, conn);
        cmd.CommandType = CommandType.StoredProcedure;
        if (parameters != null && parameters.Length > 0)
        {
          foreach (var item in parameters)
          {
            cmd.Parameters.Add(item);
          }
        }
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable table = new DataTable();
        adapter.Fill(table);
        return table;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
  }

注意,我们在

这个实现类中定义了一个私有方法,指明了数据库访问的上下文DbContext

DbContext类如下:

public class DbContext : System.Data.Entity.DbContext
  {
     static DbContext()
    {
      //Database.SetInitializer(new CreateDatabaseIfNotExists<PersonalDbContext>());
    }
     public DbContext()
      : base("Name=DbContext")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
      .Where(type => !String.IsNullOrEmpty(type.Namespace))
      .Where(type => type.BaseType != null && type.BaseType.IsGenericType &&
        type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
      foreach (var type in typesToRegister)
      {
        dynamic configurationInstance = Activator.CreateInstance(type);
        modelBuilder.Configurations.Add(configurationInstance);
      }
    }
  }

我们将Name=DbContext 意思是去寻找webconfig中具有相同名称的值 ,所以,我们在配置文件中配置该项如下:

再configuration节点下面新建

<connectionStrings>
  <add name="DbContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=Test;Uid=sa;Pwd=sa;"/>
 </connectionStrings>

忘了说,这里对实现类中的一些扩展方法做了延伸,新建一个DynamicQueryable类,代码如下:

public static class DynamicQueryable
  {
    public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
    {
      return (IQueryable<T>)Where((IQueryable)source, predicate, values);
    }
    public static IQueryable Where(this IQueryable source, string predicate, params object[] values)
    {
      if (source == null) throw new ArgumentNullException("source");
      if (predicate == null) throw new ArgumentNullException("predicate");
      LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
      return source.Provider.CreateQuery(
        Expression.Call(
          typeof(Queryable), "Where",
          new Type[] { source.ElementType },
          source.Expression, Expression.Quote(lambda)));
    }
    public static IQueryable Select(this IQueryable source, string selector, params object[] values)
    {
      if (source == null) throw new ArgumentNullException("source");
      if (selector == null) throw new ArgumentNullException("selector");
      LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
      return source.Provider.CreateQuery(
        Expression.Call(
          typeof(Queryable), "Select",
          new Type[] { source.ElementType, lambda.Body.Type },
          source.Expression, Expression.Quote(lambda)));
    }
    public static IQueryable<dynamic> Select<T>(this IQueryabl		

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。