亲宝软件园·资讯

展开

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

陈逸子风 人气:0
想了解C#实现文件上传以及多文件上传功能的相关内容吗,陈逸子风在本文为您仔细讲解C#文件上传的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#文件上传,C#多文件上传,C#上传,下面大家一起来学习吧。

一、前端搭建

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

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 里设置的文件上传最大值一样(不能大于这个值)

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

加载全部内容

相关教程
猜你喜欢
用户评论