Ajax文件上传

UI

<iframe id="upIframe" name="upIframe" frameborder="0" src="" style="display:none;"></iframe>
<form id="UploadPrjForm" method="post" action="/FileUtil/UploadPrjFile" enctype="multipart/form-data">
    <label>上传Excel:</label> <input name="pf_excel" type="file" /><br /><br />
    <label>上传 CAD:</label> <input name="pf_cad" type="file" /><br /><br />
    <input type="hidden" name="prjID" value="1" />
    <input type="button" name="uploadpf" onclick="uploadPrjFile();" value="上传" />
</form>

JS

uploadPrjFile: function(){
    $("#UploadPrjForm").ajaxSubmit({
        target: "#upIframe",
        dataType: 'script',
        success: function(data){
            if(uFile != undefined){
               alert(uFile.Message);
            }
            else{
                alert("上传错误");
            }
        }
    });
    return false;	
}

MVC

[HttpPost]
public ActionResult UploadPrjFile()
{
    string rtJs = string.Empty;
    try
    {
        //处理文件上传逻辑
         HttpPostedFileBase file = Request.Files[0];
        rtJs = "Status:true,Message:'上传成功'";
    }
    catch (Exception ex)
    {
        rtJs = "Status:false,Message:'" + ex.Message + "'";
    }
    rtJs = "var uFile = {" + rtJs + "}";
    return Content(rtJs);
}


说明

  1. UI必须引用AjaxForm插件,以异步提交表单;
  2. ajax返回类型(datatype)必须为script才能正常获取服务器返回的内容,这里为MVC部分的rtJs

你可能感兴趣的:(exception,mvc,Ajax,function,Excel,input)