MVC中基于Ajax和HTML5实现文件上传功能

2019-09-14 07:04:49王冬梅

在该方法中,发送表单,使用Form 数据对象来序列化文件值,我们可以手动创建formdata数据的实例化,通过调用append()方法将域值挂起,或是通过检索HTML 表单的FormData对象。

progressHandlingFunction方法会提供检验上传文件Size 是否可计算,使用e.loaded和e.total计算出已上传百分之多少的数据。

function progressHandlingFunction(e) {
     if (e.lengthComputable) {
       var percentComplete = Math.round(e.loaded * / e.total);
       $("#FileProgress").css("width", 
       percentComplete + '%').attr('aria-valuenow', percentComplete);
       $('#FileProgress span').text(percentComplete + "%");
     }
     else {
       $('#FileProgress span').text('unable to compute');
    }
  }

现在已经实现了基本的发送数据及提供进度条的功能,接下来需要实现服务器端的代码处理,使用upload action方法和uplpader controller 。

在upload 方法中,可以从HttpPostedfileBase对象中获取文件信息,该对象包含上传的文件的基本信息如Filename属性,Contenttype属性,inputStream属性等内容,这些信息都可以用来验证服务器端接收的文件是否有错,也可以用来保存文件。        

 public JsonResult Upload(HttpPostedFileBase uploadedFile)
       {
         if (uploadedFile != null && uploadedFile.ContentLength > )
         {
           byte[] FileByteArray = new byte[uploadedFile.ContentLength];
           uploadedFile.InputStream.Read(FileByteArray, , uploadedFile.ContentLength);
           Attachment newAttchment = new Attachment();
          newAttchment.FileName = uploadedFile.FileName;
          newAttchment.FileType = uploadedFile.ContentType;
          newAttchment.FileContent = FileByteArray;
          OperationResult operationResult = attachmentManager.SaveAttachment(newAttchment);
          if (operationResult.Success)
          {
            string HTMLString = CaptureHelper.RenderViewToString
            ("_AttachmentItem", newAttchment, this.ControllerContext);
            return Json(new
            {
              statusCode = ,
              status = operationResult.Message,
              NewRow = HTMLString
            }, JsonRequestBehavior.AllowGet);
          }
          else
          {
            return Json(new
            {
              statusCode = ,
              status = operationResult.Message,
              file = uploadedFile.FileName
            }, JsonRequestBehavior.AllowGet);
          }
        }
        return Json(new
        {
          statusCode = ,
          status = "Bad Request! Upload Failed",
          file = string.Empty
        }, JsonRequestBehavior.AllowGet);
      }

 能否通过拖拽操作实现多个文件上传的功能?

在这一部分,实现相同的uploader,并为uploader添加一些新功能:

允许选择多个文件
拖拽操作