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

function UploadFile() { //we can create form by passing the form to Constructor of formData object //or creating it manually using append function //but please note file name should be same like the action Parameter //var dataString = new FormData(); //dataString.append("UploadedFile", selectedFile); var form = $('#FormUpload')[]; var dataString = new FormData(form); $.ajax({ url '/Uploader/Upload', //Server script to process data type 'POST', xhr function () { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Check if upload property exists //myXhr.upload.onprogress = progressHandlingFunction myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload } return myXhr; }, //Ajax events success successHandler, error errorHandler, completecompleteHandler, // Form data data dataString, //Options to tell jQuery not to process data or worry about content-type. cache false, contentType false, processData false }); }

在该方法中,发送表单,使用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添加一些新功能:

允许选择多个文件
拖拽操作
现在给Uplodaer View添加新功能:

为输入文件元素添加多个属性,实现同时选择多个文件。

添加实现拖拽功能的文件,如以下代码所示:

<div>Drop images Here</div>

在JS方法MultiplefileSelected中添加onChange事件,与之前SingleFileSelected的写法类似,不同的是需要将所有的文件列出,并允许拖拽文件。代码如下:

function MultiplefileSelected(evt) { evt.stopPropagation(); evt.preventDefault(); $('#drop_zone').removeClass('hover'); selectedFiles = evt.target.files || evt.dataTransfer.files; if (selectedFiles) { $('#Files').empty(); for (var i = ; i < selectedFiles.length; i++) { DataURLFileReader.read(selectedFiles[i], function (err, fileInfo) { if (err != null) { var RowInfo = '<div><div>' + '<div>' + err + '</div>' + '<div data-name="FileName">' + fileInfo.name + '</div>' + '<div data-type="FileType">' + fileInfo.type + '</div>' + '<div data-size="FileSize">' + fileInfo.size() + '</div></div><hr/></div>'; $('#Files').append(RowInfo); } else { var image = '<img src="' + fileInfo.fileContent + '" title="' + fileInfo.name + '" />'; var RowInfo = '<div><div>' + '<div data_img="Imagecontainer">' + image + '</div>' + '<div data-name="FileName">' + fileInfo.name + '</div>' + '<div data-type="FileType">' + fileInfo.type + '</div>' + '<div data-size="FileSize">' + fileInfo.size() + '</div></div><hr/></div>'; $('#Files').append(RowInfo); } }); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfyjff.html