对于文件上传来说,有很多种实现方式,如传统的表单方式,现在流行的flash方式,甚至还有纯JS方式,之所以有这些方式来实现文件上传,我想主要原因是因为,传统的上传对于大文件支持不够,因为它是单线程同步机制,当大文件通过HTTP方式发送到服务端时,对于服务端站点的主线程影响比较大,会产生阻塞,所以,现在很多上传控制都是异步,多线程的方式去实现的.

今天来介绍一个文件上传控制,它就是Uploadify,它应该是flash的异步上传工具,对于大文件支持还不错,所以,我选择了它.

<div>
 <div class="inputDiv fl">
 <input type="text" name="ImagePath" id="ImagePath" style="width: 600px;">
 <img style="display: none;" />
 </div>
 <div class="fl" style="position: relative;">
 <input id="custom_file_uploadEdu" type="file" class="btn" />
 <a href="javascript:$('#custom_file_uploadEdu').uploadifyUpload()">上传</a>| 
 <a href="javascript:$('#custom_file_uploadEdu').uploadifyClearQueue()">取消上传</a>
 </div>
 <div id="displayMsg"></div>
</div>

JS代码

<script type="text/ecmascript">

 $("#custom_file_uploadEdu").uploadify({
 'uploader': '/Scripts/Uploadify/uploadify.swf',
 'script': '/ashx/UploadFile.ashx',
 'cancelImg': '/Scripts/Uploadify/uploadify-cancel.png',
 'folder': '/',
 'queueSizeLimit': 1,
 'simUploadLimit': 1,
 'sizeLimit ': 1024 * 1024 * 5,
 'multi': false,
 'auto': false,/*如果是自动上传,那上传按钮将没用了*/
 'fileExt': '*.jpg;*.gif;*.jpeg;*.mp4',
 'fileDesc': '请选择图像或者视频',
 'queueID': 'fileQueue',
 'width': 110,
 'height': 30,
 'buttonText': '选择',
 'wmode': 'opaque',
 'hideButton': false,
 'onSelect': function (event, ID, fileObj) {
  $("#displayMsg").html("上传中......");
 },
 'onComplete': function (event, queueId, fileObj, response, data) {
  var ary = response.split('|');
  if (ary[0] == "0") { //提示错误信息
  alert(ary[1]);
  }
  else {
  if (ary[0]=="1") {//上传后的URL
   $("#displayMsg").html("上传成功")
   $("#ImagePath").attr("value", ary[1]);
   $("#ImagePath").remove("img").next("img").show().attr({ "style": "width:50px;height:50px;", "src": ary[1] });
  } else {//异常信息
   alert(ary[1]);
  }
  }
 }
 });
</script>

后台处理程序(接收流,写入流)

namespace WebTest.ashx
{
 /// <summary>
 /// UploadFile 的摘要说明
 /// </summary>
 public class UploadFile : IHttpHandler
 {
 public void ProcessRequest(HttpContext context)
 {
  context.Response.ContentType = "text/plain";

  context.Response.Write(new UploadImpl().Upload(context, UpLoadType.ProductImage, false));

 }

 public bool IsReusable
 {
  get
  {
  return false;
  }
 }
 }

}

UploadImpl类代码

namespace EntityFrameworks.Application.Core.FileUpload
{

 /// <summary>
 /// 图像上传功能的实现
 /// </summary>
 public class UploadImpl
 {
 public UploadImpl(IFileUploadSize fileUploadSize)
 {

  _fileUploadSize = fileUploadSize ?? new TestFileUploadSize();
 }
 public UploadImpl()
  : this(null)
 {

 }
 #region Fields & Consts
 static string FileHostUri = System.Configuration.ConfigurationManager.AppSettings["FileHostUri"]
  ?? HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority;

 Point point = new Point(0, 0); //图像从那个坐标点进行截取
 double wRate = 1, hRate = 1, setRate = 1;
 int newWidth = 0, newHeight = 0;
 IFileUploadSize _fileUploadSize;
 #endregion

 #region 图像缩放
 /// <summary>
 /// 图像的缩放
 /// </summary>
 /// <param name="file">缩放文件</param>
 /// <param name="width">宽</param>
 /// <param name="height">高</param>
 /// <param name="isEqualScale">是否等比例缩放</param>
 /// <param name="name">缩放后存放的地址</param>
 /// <returns></returns>
 bool CreateThumbnail(HttpPostedFile file, ImageSize imageSize, bool isEqualScale, string name)
 {
  double width = (double)imageSize.Width;
  double height = (double)imageSize.Height; ;

  try
  {
  System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream);
  if (isEqualScale)
  {
   if (image.Height > height)
   {
   hRate = height / image.Height;
   }

   if (image.Width > width)
   {
   wRate = width / image.Width;
   }

   if (wRate != 1 || hRate != 1)
   {
   if (wRate > hRate)
   {
    setRate = hRate;
   }
   else
   {
    setRate = wRate;
   }
   }

   newWidth = (int)(image.Width * setRate);
   newHeight = (int)(image.Height * setRate);
   if (height > newHeight)
   {
   point.Y = Convert.ToInt32(height / 2 - newHeight / 2);
   }
   if (width > newWidth)
   {
   point.X = Convert.ToInt32(width / 2 - newWidth / 2);
   }

  }
  Bitmap bit = new Bitmap((int)(width), (int)(height));
  Rectangle r = new Rectangle(point.X, point.Y, (int)(image.Width * setRate), (int)(image.Height * setRate));

  Graphics g = Graphics.FromImage(bit);
  g.Clear(Color.White);
  g.DrawImage(image, r);


  MemoryStream ms = new MemoryStream();
  bit.Save(ms, ImageFormat.Jpeg);
  byte[] bytes = ms.ToArray();
  string fileName = name + imageSize.ToString();//为缩放图像重新命名
  using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  {
   stream.Write(bytes, 0, bytes.Length);
  }
  bit.Dispose();
  ms.Dispose();
  image.Dispose();
  return true;
  }
  catch (Exception)
  {
  return false;
  }
 }
 /// <summary>
 /// 图像的等比例缩放,默认文件名不改变,会将原文件覆盖
 /// </summary>
 /// <param name="file"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <returns></returns>
 bool CreateThumbnail(HttpPostedFile file, ImageSize imageSize, string name)
 {
  return CreateThumbnail(file, imageSize, true, name);
 }
 #endregion

 public string Upload(HttpContext context, UpLoadType type, bool isScale)
 {

  ImageSize imageSize = _fileUploadSize.ImageSizeForType[type];

  HttpFileCollection files = context.Request.Files;

  if (files.Count == 0)
  {
  throw new ArgumentNullException("please choose file for upload.");
  }

  string path = "/upload/" + type.ToString();//相对路径

  if (!Directory.Exists(path))
  Directory.CreateDirectory(path);
  // 只取第 1 个文件
  var file = files[0];

  if (file != null && file.ContentLength > 0)
  {

  try
  {
   string filename = context.Request.Form["fileName"].Split('.')[0]
   + "_"
   + DateTime.Now.ToString("yyyyMMddhhssmm")
   + imageSize.ToString();

   // 本地文件系统路径
   string savePath = Path.Combine(context.Server.MapPath(path), filename);
   file.SaveAs(savePath);
   if (isScale)
   CreateThumbnail(file, imageSize, savePath);

   //返回URI路径
   string ImageUri = FileHostUri
   + path
   + "/"
   + filename;

   return "1|" + ImageUri;
  }
  catch (Exception ex)
  {

   return "0|" + ex.Message;
  }

  }
  return null;
 }

 }
}

效果图:

为大家推荐一个专题,供大家学习:《ASP.NET文件上传汇总》

以上就是关于ASP.NET文件上传控件Uploadify的第一部分内容介绍,接下来还有更新,希望大家不要错过。

点赞(0)

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部