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

时间:2021-03-09 13:11:12

网上有各种各样的文件上传方法,有基于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"); } }