jquery ajax file upload NET MVC 无刷新文件上…

2018-06-22 06:19:59来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

网上有各种各样的文件上传方法,有基于JS框架的、也有基于flash swf插件的。

这次分享一个比较简单而且实用能快速上手的文件上传方法,主要步骤:

1.引用Jquery包,我用的是jquery-1.11.3.min.js 版本

2.编写JS代码

3.HTML中增加type=file控件

代码如下:

HTML代码:

    <form id="fileupload" method="post"  enctype = "multipart/form-data">
         <input type="file" id="fileid" name="fileid" accept="application/vnd.ms-excel">
     <input type="button" id="confirmuploadid" value="上传" />
</form>
//JS实现

   $('#confirmuploadid').on('click', function () {
    uploadProduct();

   });

function uploadProduct() {
    var formid = $("#fileupload");
     var fd = new FormData(formid[0]);  //form表单的方式实例化一个formData
    fd.append('file', $('#fileid')[0].files);
    fd.append('userid', userid);
    $.ajax({
        url: 'File/Setting',
        type: 'POST',
        dataType: 'JSON',
        data: fd,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $("#confirmuploadid").prop("disabled", true);
        },
        success: function (returndata) {
           $("#confirmuploadid").prop("disabled", false);
            alert(returndata.Message);
        },
        error: function (returndata) {
            alert("上传失败,请检查数据正确性,如:有些数字输入项,是否输入了字符!");
        }
    });
}        
 
//MVC实现
public class FileController : Controller { [HttpPost] public ActionResult Setting() { string userid = "1"; string username = "1"; FunctionBackMessage functionBackMessage = new FunctionBackMessage(); functionBackMessage.IsSuccess = false; functionBackMessage.Message="上传失败,稍后重试!"; if (!string.IsNullOrEmpty(username)) { HttpFileCollectionBase files = Request.Files; string _urlstr = Request.Url.AbsoluteUri; FunctionBackMessage fc = new FunctionBackMessage(); fc.IsSuccess = true; fc.Message = "上传成功"; if (files.AllKeys.Length > 0) { for (int i = 0; i < files.AllKeys.Length; i++) { var myFile = files[i]; double myFileLength = myFile.ContentLength / 1024.0 / 1024.0; int InputMediaExcelLength = !string.IsNullOrEmpty(Global.GetAppString("InputMediaExcelLength")) ? int.Parse(Global.GetAppString("InputMediaExcelLength")) : 50; if (myFileLength > InputMediaExcelLength)//超出指定大小 { fc.IsSuccess = false; fc.Message = "为了保证数据处理效率,每次上传文件小于" + InputMediaExcelLength + "M,如超出请拆分记录分多次上传!"; } else { // string projectId = context.Request["projectId"]; // string username = context.Request["username"]; if ((!Path.GetExtension(myFile.FileName).Contains("xls") && !Path.GetExtension(myFile.FileName).Contains("xlsx"))) { functionBackMessage.IsSuccess = false; functionBackMessage.Message = "请上传Excel格式文件!"; return Json(functionBackMessage, "application/json"); } //文件保存 string uploadPath = HttpContext.Current.Server.MapPath("/tempfile") + "\\";//服务器临时路径(不含文件名和后缀) if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string fileName = DateTime.Now.Ticks + "_" + myFile.FileName; string fileFull = uploadPath + fileName;//文件路径,包含文件名和后缀 try { myFile.SaveAs(fileFull);//保存文件 } catch (Exception ex) { com.log.Loger.Debug("uploadMediaSource 保存文件失败", ex); } } } } else { functionBackMessage.IsSuccess = false; functionBackMessage.Message = "没有获取到上传文件"; } } return Json(functionBackMessage, "application/json"); } }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:容器化现有ASP.NET MVC 5应用

下一篇:mvc中的action验证登录(ActionFilterAttribute)