jquery + .net mvc3.0 + 无刷新上传文件

来源:互联网 发布:知行天下 编辑:程序博客网 时间:2024/04/29 02:11
 

jquery + .net mvc3.0 + 无刷新上传文件

----- 概述 -----
1.HTML中 id="form_upload" 表单的target 属性要指向页面中不可见的 iframe( id="hidden_frame")
  这样提交到 ifrmae 中的请求会刷新这个不可见的帧

2.使用 TestSubmit() 方法提交数据就是因为方便传一些自定义的参数(currentPath)
3.服务器端的代码自己去研究吧!注意的是如果成功需要调用一个回调函数 UploadCallback
  刷新页面,这个回调函数要写在响应流中
---------------- 

一、HTML 内容
    <!--begin 上传文件-->
    <div id="divFileUpload" icon="icon-up" style="padding:5px;width:400px;height:200px;">
        <form action="UploadFile.aspx" id="form_upload" name="form_upload" encType="multipart/form-data"  method="post" target="hidden_frame" >  
            <input type="file" id="file_upload" name="file_upload" style="width:450">  
            <span id="upload_msg"></span>  
     <input type="button" value="上传" onclick="TestSubmit();">
            <br>  
            <font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上传</font>                
            <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>  
        </form>
    </div>
    <!--end 上传文件-->

二、页面脚本
<script language="javascript">
//上传后的回调函数(上传文件的输出流调用)
function UploadCallback(msg)
{
    //    document.getElementById("form_upload").outerHTML = document.getElementById    $("form_upload").outerHTML;
    if(msg=="false")
    {
        alert("文件上传失败!");
        return;
    }
    $("#form_upload").val("");
    $('#divFileUpload').dialog('close');
    ReloadGridData();
}

function TestSubmit()
{
  $("#form_upload")
  .first()
  .attr("action", "UploadFile.aspx?currentPath=" + m_currentPath)
  .submit();
}
</script>

三、在 Global.asax 文件中配置的路由

      routes.MapRoute(
        "Default01", // 路由名称
        "{controller}/{action}.aspx/id", // 带有参数的 URL
        new { controller = "Explorer", action = "Index", id = UrlParameter.Optional } // 参数默认值
      );

四、.NET MVC 中控制器内的方法

public class ExplorerController : Controller
{
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public string UploadFile(string currentPath)
    {
      if (currentPath.IsNullOrEmpty())
        return "false";

      string filename = string.Empty;
      string path = string.Empty;
      foreach (string upload in Request.Files)
      {
        if (!Request.Files[upload].HasFile())
          continue;

        filename = Path.GetFileName(Request.Files[upload].FileName);
        path = Path.Combine(currentPath.UrlDecode(), filename);
        Request.Files[upload].SaveAs(path);
        if (System.IO.File.Exists(path))
        {
          Response.Output.WriteLine("<script language='javascript'>parent.UploadCallback('true')</script>");
          return "true";
        }
        else
        {
          Response.Output.WriteLine("<script language='javascript'>parent.UploadCallback('false')</script>");
          return "false";
        }
      }

      return "false";
    }
}

原创粉丝点击