MVC中上传图片文件

MVC的控制器如何获取input(file)的值,将图片保存到项目文件中

View视图中:

(1)在xxxx.cshtml中加入表单内容,在<form>中一定要加入enctype="multipart/form-data" 属性

<link rel="stylesheet" type="text/css" href="../../Scripts/bmms_EasyUI/themes/gray/easyui.css">
<link rel="stylesheet" type="text/css" href="../../Scripts/bmms_EasyUI/themes/icon.css">
<script type="text/javascript" src="../../Scripts/bmms_EasyUI/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/bmms_EasyUI/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../Scripts/bmms_EasyUI/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="../../Scripts/bmms.javascript/News.js"></script>

<form id="form1"  method="post" enctype="multipart/form-data">
  上传图片: <input type="file" class="easyui-filebox" id="image" name="File" />
   <a href="#" id="saveNews" style="float: right" class="easyui-linkbutton"  iconcls="">提交</a>
</form>
(2)在News.js的文件

$(function () {
 
    $('#saveNews').linkbutton().click(function () {
        
        $('#form1').form('submit', {
            url: "/Architecture_New/NewSave/",
            onSubmit: function () {
                return $(this).form('validate');
            },
            success: function (result) {
              
                if (result) {
                   
                    $.messager.alert("提示", "恭喜您,保存成功", "info");
                    $('#form1').form('clear');
                }
                else {
                    $.messager.alert("提示", "添加失败,请重新操作(请检查图片是否为空)!", "info");
                     //return;

                }


            }
        });


    });



});
(3)在控制器Architecture_New中,加入以下方法(需要新建文件夹 Upload

       [HttpPost]
        public Boolean NewSave()
        {
            HttpFileCollectionBase files = Request.Files;
            HttpPostedFileBase File = files["File"];
            string FileName = File.FileName; //上传的原文件名
            string guid="";
            if (FileName != null && FileName!= "")
            {
                string FileType = FileName.Substring(FileName.LastIndexOf(".") + 1); //得到文件的后缀名
                guid = System.Guid.NewGuid().ToString() + "." + FileType; //得到重命名的文件名
                File.SaveAs(Server.MapPath("/Upload/") + guid); //保存操作

            }
            return true;
        }









你可能感兴趣的:(mvc,上传图片,表单,文件保存)