当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET文件上传控件Uploadify的使用方法

ASP.NET文件上传控件Uploadify的使用方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

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

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

相关api介绍

uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字browse的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf。
script :   后台处理程序的相对路径 。默认值:uploadify.php
checkscript :用来判断上传选择的文件在服务器是否存在的后台处理程序的相对路径
filedataname :设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为filedata
method : 提交方式post 或get 默认为post
scriptaccess :flash脚本文件的访问模式,如果在本地测试设置为always,默认值:samedomain 
folder :  上传文件存放的目录 。
queueid : 文件队列的id,该id与存放文件队列的div的id一致。
queuesizelimit : 当允许多文件生成时,设置选择文件的个数,默认值:999 。
multi : 设置为true时可以上传多个文件。
auto : 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。

fileext : 设置可以选择的文件的类型,格式如:'*.jpg;*.gif,*.png' 。

filedesc : 这个属性值必须设置fileext属性后才有效,用来设置选择文件对话框中的提示文本,如设置filedesc为“请选择图像文件”,
sizelimit : 上传文件的大小限制 。
simuploadlimit : 允许同时上传的个数 默认值:1 。
buttontext : 浏览按钮的文本,默认值:browse 。
buttonimg : 浏览按钮的图片的路径 。
hidebutton : 设置为true则隐藏浏览按钮的图片 。
rollover : 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。
width : 设置浏览按钮的宽度 ,默认值:110。
height : 设置浏览按钮的高度 ,默认值:30。
wmode : 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。
cancelimg :选择文件到文件队列中后的每一个文件上的关闭按钮图标

结构图

html代码

<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的第一部分内容介绍,接下来还有更新,希望大家不要错过。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网