asp.net异步上传

界面如下:

技术分享

需要用到MyAjaxForm.js库

 

<script src="~/Scripts/MyAjaxForm.js"></script>

 @using (Ajax.BeginForm("AjaxAddUserPrintReport", "Admin", new AjaxOptions() { HttpMethod = "post", LoadingElementId = "loading", OnSuccess = "afterOk",OnFailure="afterErr" }, new { id = "addform", @class = "form-horizontal", enctype = "multipart/form-data" }))
    {

<div class="form-group"> <label for="uploadfile" class="col-md-2 control-label"> 上传文件:</label> <div class="col-md-4"> <textarea class="form-control hidden" id="Uploadfileurl" name="Uploadfileurl" rows="3"></textarea> <input type="file" id="fileup" name="fileup" /> <button type="button" id="btnupload" class="btn btn-warning btn-sm">上传</button> </div> <div id="showfile" class="col-md-4"> </div> </div>
}


  //点击上传文件
        $("#btnupload").click(function () {
            if ($(":file").val() == "")
            {
                alert("请选择上传文件后再点击上传按钮");
                return;
            }
            $("#addform").ajaxSubmit({
                error: function (error) { alert(error); },
                url: /Admin/AjaxUploadFile,
                type: "post",
                success: function (data) {
                    var arr = data.split(":");
                    if (arr[0] == "ok") {
                        $("#Uploadfileurl").val($("#Uploadfileurl").val().trim()==""?arr[1]: $("#Uploadfileurl").val()+ "," + arr[1]);
                        addfile();
                    }
                    else {
                        alert(arr[1]);
                    }
                }                
            });
        });

 MVC中上传代码如下:

 /// <summary>
        /// 上传文件,最大上传10M
        /// </summary>
        /// <returns></returns>

public ActionResult AjaxUploadFile() { try { HttpPostedFileBase uploadfile = Request.Files["fileup"]; if (uploadfile == null) { return Content("no:非法上传"); } if (uploadfile.FileName == "") { return Content("no:请选择文件"); } if (uploadfile.ContentLength > 10 * 1024 * 1024) { return Content("no:上传文件超过10M,实际上传大小为" + uploadfile.ContentLength); } string filename = Path.GetFileName(uploadfile.FileName); string fileExt = Path.GetExtension(filename); StringBuilder sbtime = new StringBuilder(); sbtime.Append(DateTime.Now.Year).Append(DateTime.Now.Month).Append(DateTime.Now.Day).Append(DateTime.Now.Hour).Append(DateTime.Now.Minute).Append(DateTime.Now.Second); string dir = "/UploadFile/" + getUserBySession().Name + "/" + filename.Substring(0, filename.LastIndexOf(".")) + "_" + sbtime.ToString() + fileExt; string realfilepath = Request.MapPath(dir); string readDir = Path.GetDirectoryName(realfilepath); if (!Directory.Exists(readDir)) Directory.CreateDirectory(readDir); uploadfile.SaveAs(realfilepath); return Content("ok:" + dir); } catch (Exception ex) { return Content("no:" + ex.Message); }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。