博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC + ajaxform 文件上传
阅读量:7047 次
发布时间:2019-06-28

本文共 6147 字,大约阅读时间需要 20 分钟。

一、前端cshtml代码

                添加附件:                @using (Html.BeginForm("FileUp", "Detail", FormMethod.Post, new { enctype = "multipart/form-data", id = "formFileUpload" }))                {                                                                                                                                                                                                                    }                                     

二、JS代码

(function () {    var replyJs = replyJs || {};    replyJs.unitls = (function () {        var controller = '/RenosData.Fax.Web/Detail';        var homeController = '/RenosData.Fax.Web/Home';        //传真回复        var replyFax = function () {            //浏览附件            $("#btnSee").bind("click", function (e) {                $("#uploadFile").click();            });            //上传附件            $("#uploadFile").bind("change", function (e) {                $("#filePath").val($("#uploadFile").val());            });            $("#btnUploadFile").click(function () {                addAttachment();                return false;            });            //删除传真附件            $("#btnDelAttach").live("click",function () {                $.ajax({                    url: controller + '/DelAttachment',                    type: 'post',                    //dataType: 'json',                    data: "{file:'" + $(this).attr("filename") + "'}",                    contentType: 'application/json; charset=utf-8',                    success: function (data) {                        if (data.status == "success") {                            $("#attachMents").empty();                        } else {                            alert(data.message);                        }                    },                    error: function (err) {                        alert(err.toString());                    }                });            });            //发送传真            $("#btnSendFax").click(function () {                addFaxToDb("send");            });         };        //上传附件        var addAttachment = function () {            if (!$("#filePath").val()) {                alert("请选择需要上传的文件!");                return;            }             //function showRequest(formData, jqForm, options) {
// //alert('发送前'); // return true; //} //function showResponse(responseText, statusText) { // //alert('发送后'); //} //var options = {
// //target: '#outputdiv', // beforeSubmit: showRequest, // success: showResponse //}; //$(this).ajaxSubmit(options); $("#formFileUpload").ajaxSubmit({ dataType: 'json', beforeSend: function (xhr) { }, success: function (data) { if (data) { if (data.message == "success") { $("#filePath").val(""); $("#attachMents").empty().append("已上传附件:"); } else { alert(data.message); } } }, complete: function () { } }); return; }; //传真状态:发送or保存 var back = function () { window.history.go(-1); }; return { replyFax: replyFax, }; }()); $(function () { replyJs.unitls.replyFax(); });})(jQuery);

三、Controller代码

///         /// 添加附件        ///         /// 
[HttpPost] public ActionResult FileUp() { HttpPostedFileBase uploadFile = Request.Files[0]; var fax = new FaxModel(); if (uploadFile == null || uploadFile.ContentLength == 0) { fax = new FaxModel() { Message = "请选择上传附件!", Attachment = null }; return Json(new { message = fax.Message }); } //if (uploadFile.ContentLength > 20971520) //{ // fax = new FaxModel() { Message = "请上传20MB以内的附件!", Attachment = null }; // return View("NewFax", fax); //} try { var newFileName = Guid.NewGuid() + "_" + uploadFile.FileName; ; string attachFilePath = WebConfig.Attachment; if (!Directory.Exists(attachFilePath)) Directory.CreateDirectory(attachFilePath); string filePath = Path.Combine(attachFilePath, newFileName); uploadFile.SaveAs(filePath); var attachment = new FileAttachmentModel() { FileName = newFileName, FileLength = (uploadFile.ContentLength * 1.0 / 1024).ToString("0.00"), FilePath = filePath, FileOldName = uploadFile.FileName, FileSize = uploadFile.ContentLength }; fax = new FaxModel() { Attachment = attachment }; ViewBag.FaxMsg = uploadFile.FileName; return Json(new { message = "success", fileOldName = attachment.FileOldName, fileSize = attachment.FileSize, fileName = attachment.FileName }); } catch (Exception) { return Json(string.Empty); } }

附件删除

///         /// 附件删除        ///         ///         /// 
[HttpPost] public ActionResult DelAttachment(string file) { try { string attachFilePath = WebConfig.Attachment; string filePath = Path.Combine(attachFilePath, file); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); return Json(new { status = "success" }); } return Json(new { status = "false", message = "附件删除失败!" }); } catch (Exception ex) { return Json(new { status = "false", message = "附件删除失败!" }); } }

 

 

 

转载地址:http://tlzol.baihongyu.com/

你可能感兴趣的文章
Using the Eclipse Jobs-API(转载)
查看>>
GCC编译过程
查看>>
AE intersect、clip的实现
查看>>
图解使用Win8Api进行Metro风格的程序开发一----建立我们的导航架构
查看>>
iOS开发过程中使用Core Data应避免的十个错误
查看>>
I.MX6 wpa_cli 使用
查看>>
windows使用nginx实现网站负载均衡测试实例
查看>>
DotLiquid模板引擎简介
查看>>
5.Flask-Migrate
查看>>
c# 正则表代式的分组和批评模式 .
查看>>
编程之美-3.1-字符串移位包含的问题
查看>>
EPC是什么
查看>>
T-SQL查询进阶--数据集之间的运算
查看>>
【Vegas原创】Linux下unrar安装与配置
查看>>
HDOJ 2095(找出唯一的出现一次的数)
查看>>
java面试32问
查看>>
钟翔平:坚持走手机浏览器架构创新之路
查看>>
图片处理--浮雕特效
查看>>
chr() ord() 的用法
查看>>
C++对象模型简介(二)——深入底层,探索本质
查看>>