当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现文件上传以及多文件上传功能

C#实现文件上传以及多文件上传功能

2019年07月18日  | 移动技术网IT编程  | 我要评论

一、前端搭建

1、前端用到js:uploadify(下载地址:)、layer (下载地址:),下载之后把它们放在你的项目里 列如

2、根据你的需要在你项目适当的位置建立上传文件的目录  列如(file)

 到此前端搭建结束

二、配置文件修改(可选择跳过此步骤)

1、首先说明下,这个步骤可以跳过,此步骤主要是修改上传文件大小的限制(.net 默认最大只能上传4m)如若需要修改请继续阅读该步骤。

2、打开web.config 配置文件 找到<system.web> 节点 ,在该节点下面添加如下节点

<httpruntime targetframework="4.5"  executiontimeout="500" maxrequestlength="409600" usefullyqualifiedredirecturl="false" minfreethreads="8" minlocalrequestfreethreads="4" apprequestqueuelimit="100" />
<!-- maxrequestlength属性是上传文件大小的设置 值是kb大小 maxrequestlength=“1024” 为最大上传1m -->

三、代码编写

1、说明下:我用的是mvc模式 所以这里就用mvc的方式编写 (代码是不变的,开发者可以根据你们的设计模式编写)

2、建立一个控制器pagebasecontroller在该控制器里编写如下代码 (如果是用的aspx页面那么把fileupdateview方法删掉  ,把uploadifyfile 方法的actionresult改成void  并去掉return null;) 

后端代码如下

/// <summary>
    /// 文件上传页面
    /// </summary>
    /// <returns></returns>
    public actionresult fileupdateview()
    {
      return view();
    }

    /// <summary>
    /// 文件处理方法
    /// </summary>
    /// <param name="filedata"></param>
    /// <returns></returns>
    public actionresult uploadifyfile(httppostedfilebase filedata)
    {
      if (filedata == null ||
        string.isnullorempty(filedata.filename) ||
        filedata.contentlength == 0)
      {
        return httpnotfound();
      }

      string filename = system.io.path.getfilename(filedata.filename);
      string virtualpath = string.format("~/file/{0}", filename);

      string path = server.mappath(virtualpath);
      // 以下注释的代码 都可以获得文件属性
      // system.diagnostics.fileversioninfo info = system.diagnostics.fileversioninfo.getversioninfo(path);
      // fileinfo file = new fileinfo(filedata.filename);

      filedata.saveas(path);
      return null;
    } 

注:virtualpath 是我们搭建上传文件的目录

3、在视图(页面)里引用我们搭建的js:uploadfiy 、layer 路径

 列如:      

<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/lib/layer/layer.js"></script>
<link href="~/scripts/lib/uploadify/uploadify.css" rel="external nofollow" rel="stylesheet" />
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script src="~/scripts/lib/uploadify/jquery.uploadify.min.js"></script>

注:这里我们用到了jquery

4、前端代码

<script type="text/javascript">
  var uploadifyonselecterror;
  var uploadifyonuploaderror;
  var uploadifyonselect;
  var uploadifyonuploadsuccess;
  uploadifyonselecterror = function (file, errorcode, errormsg) {
    var msgtext = "上传失败\n";
    switch (errorcode) {
      case swfupload.queue_error.queue_limit_exceeded:
        //this.queuedata.errormsg = "每次最多上传 " + this.settings.queuesizelimit + "个文件";
        msgtext += "每次最多上传 " + this.settings.queuesizelimit + "个文件";
        break;
      case swfupload.queue_error.file_exceeds_size_limit:
        msgtext += "文件大小超过限制( " + this.settings.filesizelimit + " )";
        break;
      case swfupload.queue_error.zero_byte_file:
        msgtext += "文件大小为0";
        break;
      case swfupload.queue_error.invalid_filetype:
        msgtext += "文件格式不正确,仅限 " + this.settings.filetypeexts;
        break;
      default:
        msgtext += "错误代码:" + errorcode + "\n" + errormsg;
    }
    layer.msg(msgtext);
  };
  uploadifyonuploaderror = function (file, errorcode, errormsg, errorstring) {
    // 手工取消不弹出提示
    if (errorcode == swfupload.upload_error.file_cancelled
      || errorcode == swfupload.upload_error.upload_stopped) {
      return;
    }
    var msgtext = "上传失败\n";
    switch (errorcode) {
      case swfupload.upload_error.http_error:
        msgtext += "http 错误\n" + errormsg;
        break;
      case swfupload.upload_error.missing_upload_url:
        msgtext += "上传文件丢失,请重新上传";
        break;
      case swfupload.upload_error.io_error:
        msgtext += "io错误";
        break;
      case swfupload.upload_error.security_error:
        msgtext += "安全性错误\n" + errormsg;
        break;
      case swfupload.upload_error.upload_limit_exceeded:
        msgtext += "每次最多上传 " + this.settings.uploadlimit + "个";
        break;
      case swfupload.upload_error.upload_failed:
        msgtext += errormsg;
        break;
      case swfupload.upload_error.specified_file_id_not_found:
        msgtext += "找不到指定文件,请重新操作";
        break;
      case swfupload.upload_error.file_validation_failed:
        msgtext += "参数错误";
        break;
      default:
        msgtext += "文件:" + file.name + "\n错误码:" + errorcode + "\n"
          + errormsg + "\n" + errorstring;
    }
    layer.msg(msgtext);
  };

  uploadifyonselect = function () {
  };
  uploadifyonuploadsuccess = function (file, data, response) {
    layer.msg(file.name + "\n\n" + response + "\n\n" + data);
  };
  $(function () {

    $("#uploadify").uploadify({
      uploader: '/pagebase/uploadifyfun', //处理上传的方法
      swf: '/scripts/lib/uploadify/uploadify.swf',
      width: 80, // 按钮宽度
      height: 60, //按钮高度
      buttontext: "上传文件",
      buttoncursor: 'hand',
      filesizelimit:20480,
      fileobjname: 'filedata',
      filetypeexts: '*.xlsx;*.docx', //扩展名
      filetypedesc: "请选择xslx,docx文件", //文件说明
      auto: false, //是否自动上传
      multi: true, //是否一次可以选中多个文件
      queuesizelimit: 5, //允许同时上传文件的个数
      overrideevents: ['onselecterror', 'ondialogclose'], // 是否要默认提示 要就不配置
      onselect: uploadifyonselect,
      onselecterror: uploadifyonselecterror,
      onuploaderror: uploadifyonuploaderror,
      onuploadsuccess: uploadifyonuploadsuccess
    });
  });
</script>
<span id="uploadify"></span>
<div>
  <a href="javascript:$('#uploadify').uploadify('upload','*');">上传</a>
  <a href="javascript:$('#uploadify').uploadify('cancel', '*');">取消</a>
</div> 

注:filesizelimit 属性的值最好和我们web.config 里设置的文件上传最大值一样(不能大于这个值)

到这里。我们文件上传就结束了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

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

相关文章:

验证码:
移动技术网