最近项目中成绩管理的老师布置作业部分,涉及到了office文件的上传和预览。经过几番折腾,终于达到预期效果。
项目是基于MVC+EsayUI实现的,在此分享一下上传文件的代码:
View:
<script src="../../Scripts/MyScript/DatagridOperate.js" type="text/javascript"></script><div id="Priview" closed="true" class="easyui-dialog" style="width: 360px; height: auto; padding-top: 30px; padding-bottom: 30px; padding-left: 25px;" buttons="#dlg-buttons" title="文件预览"> <form id="AddHomeWork" method="post" action="/TeaQueryHomework/AddHomeW"> <div id="upload" style="width: 300px; display: block; padding-bottom: 15px; padding-top: 15px;"> <input type="file" class="easyui-linkbutton" name="fileToUpload" id="fileToUpload" multiple="multiple" onchange="fileSelected();" /> <a id="" class="easyui-linkbutton" href="#" data-options="plain:true,iconCls:'icon-undo'" style="margin-left: 5px;" onclick="uploadFile()"> <span>上传</span> </a> </div> </form></div>
Controller上传文件方法:
[HttpPost][ValidateInput(false)]public string UploadFile(HttpPostedFileBase[] fileToUpload){ #region 旧版 try { string FileUrl = string.Empty; //TODDO:读取任何地方的路径 foreach (HttpPostedFileBase file in fileToUpload) { path = System.IO.Path.Combine(Server.MapPath("~/"), System.IO.Path.GetFileName(file.FileName)); //在path路径下保存文件 file.SaveAs(path ); } } catch (Exception e) { // } }
JS代码:
//选择上传文件function fileSelected() { var file = document.getElementById('fileToUpload').files[0]; var fileName = file.name; var file_typename = fileName.substring(fileName.lastIndexOf('.'), fileName.length); if (file_typename == '.xls' || file_typename == '.xlsx' || file_typename == '.doc' || file_typename == '.docx') {//这里限定上传文件文件类型 if (file) { $("#uploadFile").show(); var fileSize = 0; if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; document.getElementById('fileName').innerHTML = '文件名: ' + file.name; document.getElementById('fileSize').innerHTML = '大小: ' + fileSize; document.getElementById('fileType').innerHTML = '类型: ' + file.type; } } else { //当上传格式错误后,提示 $("#uploadFile").hide(); document.getElementById('fileName').innerHTML = "<span style='color:Red'>错误提示:上传文件应该是.xls后缀而不应该是" + file_typename + ",请重新选择文件</span>" document.getElementById('fileSize').innerHTML = ""; document.getElementById('fileType').innerHTML = ""; }}//上传文件的方法function uploadFile() { var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); //上传进度 xhr.addEventListener("load", uploadComplete, false); //上传完成 xhr.addEventListener("error", uploadFailed, false); //上传出错 xhr.addEventListener("abort", uploadCanceled, false); //取消上传 xhr.addEventListener("success", uploadSuccess, false);//上传成功 xhr.open("POST", "/TeaQueryHomework/UploadFile"); //Controller里边UploadFile方法 xhr.send(fd);}//上传文件function uploadProgress(evt) { if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); $('#progressNumber').progressbar('setValue', percentComplete); } else { document.getElementById('progressNumber').innerHTML = '无法计算'; }}//完成上传文件的操作function uploadComplete(evt) { /* 服务器返回数据*/ var message = evt.target.responseText;}//上传文件成功function uploadSuccess(evt) { /* 服务器返回数据*/ alert("上传成功.");}//上传文件失败function uploadFailed(evt) { alert("上传出错.");}//取消上传文件function uploadCanceled(evt) { alert("上传已由用户或浏览器取消删除连接.");}
文件的上传由以上几行简单的代码就能搞定了,老师布置作业,将作业上传到服务器就完成了。下一篇博客将介绍上传文件的预览功能,未完待续~~~