MVC上传文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MVC上传文件相关的知识,希望对你有一定的参考价值。
1、首先需要定义页面标签
<form id="fileUploadForm" method="post" enctype="multipart/form-data"> </form>
2、定义JQuery方法
function file_onChange(srcElement) { $("#fileUploadForm").ajaxSubmit({ type: ‘post‘, url: "/require/UpLoadFiless", data: { Upload_req00_no: $("#Upload_req00_no").val() }, success: function (result) { //上传完成后的操作 if (result != "") { result = eval("(" + result + ")"); var filenamestr = result.fileName + "." + result.fileExtension; var obj = $("#div_upload_info", parent.document) $(obj).append("<span class=‘tagstyle‘><input type=‘hidden‘ name=‘fileExtension‘ value=" + result.fileExtension + "><input type=‘hidden‘ name=‘fileName‘ value=" + result.fileName + "><input type=‘hidden‘ name=‘fileSize‘ value=" + result.fileSize + "><a href=‘#‘ onclick=‘DownloadFiles(this,\"" + filenamestr + "\",\"" + $("#Upload_req00_no").val() + "\")‘>" + result.fileName + "." + result.fileExtension + "</a><a class=‘ico-href‘ href=‘#‘><i class=‘icon-remove‘ onclick=removeTag(this)></i></a></span>"); } }, error: function (XmlHttpRequest, textStatus, errorThrown) { alert("error"); } });
3、控制器中的操作
HttpPostedFileBase uploadFile = Request.Files["file"]; if (Request.Files.Count > 0) { if (uploadFile != null) { byte[] lByteArray; MemoryStream lMemoryStream = new MemoryStream();
//将文件流拷贝到内存流中 uploadFile.InputStream.CopyTo(lMemoryStream); lByteArray = lMemoryStream.ToArray(); path = string.Empty; path = Upload_req00_no;
//获取文件后缀 fileExtension = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf(‘.‘) + 1);
//获取文件名称 fileName = uploadFile.FileName.Substring(0, uploadFile.FileName.LastIndexOf(‘.‘)); UpLoadFileModel fModel = new UpLoadFileModel();
//文件大小 fileSize = uploadFile.ContentLength;
//自定义的API服务来保存文件 base.ExecAPIService(EnumAppSettingAPIKey.APIMELMRPAttachFileUploadEventURL, fModel.GetAPIUploadEntity(path, fileName, fileExtension), lByteArray); }
以上是关于MVC上传文件的主要内容,如果未能解决你的问题,请参考以下文章