ASP.NET MVC5中的文件上传

web开发中,文件的上传是非常基本功能之一。
asp.net中,通常做法是利用webservice 来接收文件请求,这样做的好处就是全站有了一个统一的文件上传接口,并且根据网站的实际情况,可以将webservice部署到其他服务器上,可以兼容考虑将来的分布存储等等问题。

在MVC中实现文件上传主要有2中方式:

1.普通Controller实现文件上传
2.ApiController实现文件上传

普通Controller实现文件上传

在普通的Controller中实现文件上传时,需要使用到HttpPostedFileBase类来接收文件。调用HttpPostedFileBase 实例对象的SaveAs()方法,就可以将文件保存在服务器中,示例代码如下:
HTML片段:

<h2>Upload</h2>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <h4>Select a file:</h4>
        <input name="files" id="files" type="file" />
        <label id="lbError">@ViewBag.ErrorMessage</label>
        <input type="submit" name="submit" value="Upload" />
    </div>
}

Controller中的Action片段:

[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    if (files == null || files.Count() == 0 || files.ToList()[0] == null)
    {
        ViewBag.ErrorMessage = "Please select a file!!";
        return View();
    }
    string filePath = string.Empty;
    Guid gid = Guid.NewGuid();
    foreach (HttpPostedFileBase file in files)
    {
        filePath = Path.Combine(HttpContext.Server.MapPath("/Uploads/"), gid.ToString() + Path.GetExtension(file.FileName));
        file.SaveAs(filePath);
    }
    return RedirectToAction("UploadResult", new { filePath = filePath });
}
public ActionResult UploadResult(string filePath)
{
    ViewBag.FilePath = filePath;
    return View();
}

需要注意2个问题:

  1. 注意给form表单加上enctype = “multipart/form-data” 属性,否则会导致Action的参数HttpPostedFileBase 对象接收不到文件。
  2. 注意文件大小,IIS中默认上传的文件大小为4MB ,超过这大小的文件需要在修改配置文件。

上传大文件时修改文件大小限制如下:
第一步:asp.net中的文件大小限制

<system.web>
    <httpRuntime maxRequestLength="153600" executionTimeout="900" />
</system.web>

第二步:IIS中文件大小限制

<system.webServer>
    <security>
        <requestFiltering>
                <requestLimits maxAllowedContentLength="157286400" />
             </requestFiltering>
    </security>
</system.webServer>

ApiController实现文件上传

通过ApiController来实现文件上传时,不得不参考一下 官方文档了,建议先去阅读一下。
我自己在实现Demo时, 开发环境为.net 4.0。
HTML片段:

<h2>API Upload</h2>
<form name="apiForm" method="post" enctype="multipart/form-data" action="/api/upload">
    <div>
        <label for="apifiles">Select a File</label>
        <input name="apifiles" type="file" />
    </div>
    <div>
        <input type="submit" value="Upload" />
    </div>
</form>

ApiController代码:

public class UploadController : ApiController
    {
        public Task<HttpResponseMessage> PostFormData()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new Exception("");
            }
            string root = HttpContext.Current.Server.MapPath("/Uploads/");
            var provider = new ReNameMultipartFormDataStreamProvider(root);

            var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }
                string fileName = string.Empty;
                foreach (MultipartFileData file in provider.FileData)
                {
                    fileName = file.LocalFileName;
                }
                //返回上传后的文件全路径
                return new HttpResponseMessage() { Content = new StringContent(fileName) };
            });
            return task;
        }
    }

    /// <summary>
    /// 重命名上传的文件
    /// </summary>
    public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public ReNameMultipartFormDataStreamProvider(string root)
            : base(root)
        { }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            //截取文件扩展名
            string exp = Path.GetExtension(headers.ContentDisposition.FileName.TrimStart('\"').TrimEnd('\"'));
            string name = base.GetLocalFileName(headers);
            return name + exp;
        }

    }

如上代码,区别与官网给出的.net 4.0 版本的代码的。
请注意: ReNameMultipartFormDataStreamProvider 为自定义类,继承自MultipartFormDataStreamProvider, 这个累的目的就是对上传上来的文件在保存到服务器时,保留文件的扩展名。MultipartFormDataStreamProvider类默认保存的文件是没有扩展名称的。当然我自己这里实现的方式的确挺土的,演示Demo明白思议即可,呵呵。

到这里就差不多了,后面准备实现Ajax+SingR来实现文件上传时显示上传进度的Demo


通过asp.net mvc使用uploadify的示例

HomeController.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Demo.Comm;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }


        public JsonResult Upload(HttpPostedFileBase fileData)
        {
            if (fileData != null)
            {
                try
                {
                    // 文件上传后的保存路径
                    string filePath = Server.MapPath("~/Uploads/");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = Guid.NewGuid().ToString() + fileExtension; // 保存文件名称

                    fileData.SaveAs(filePath + saveName);


                    //SaveFile saveFile = new SaveFile(ConfigurationManager.AppSettings["ftpip"], "", ConfigurationManager.AppSettings["ftpuser"], ConfigurationManager.AppSettings["ftppass"]);
                    //string fullName = saveFile.GetFileFullName("", "", fileName, true);
                    //string fileUrl = saveFile.SaveFtp(fileData.InputStream, fullName);

                    return Json(new { Success = true, FileName = fileName, SaveName = filePath + saveName });
                }
                catch (Exception ex)
                {
                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {

                return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet);
            }
        }

    }
}

SaveFile.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Demo.Comm
{

    public class SaveFile
    {
        private String _ftpServerIP;
        private String _httpDomain;
        private String _ftpUserID;
        private String _ftpPassword;

        public SaveFile(string ftpServerIP, string httpDomian, string ftpUserID, string ftpPassword)
        {
            this._ftpServerIP = ftpServerIP;
            this._httpDomain = httpDomian;
            this._ftpUserID = ftpUserID;
            this._ftpPassword = ftpPassword;
        }

        public SaveFile() { }

        //创建本地文件夹
        private static void CreateDirectoryLocal(string targetDir)
        {
            DirectoryInfo dir = new DirectoryInfo(targetDir);
            if (!dir.Exists)
                dir.Create();
        }

        //创建ftp文件夹
        public bool CreateDirectoryFtp(string fpath)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(fpath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(this._ftpUserID, this._ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                WebResponse response = reqFTP.GetResponse();
                return true;
            }
            catch
            {
                return false;
            }
        }

        //判断是否是文件夹
        /// <summary>
        /// 目录是否存在
        /// </summary>
        /// <param name="fpath"></param>
        /// <returns></returns>
        public bool IsDir(string fpath)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(fpath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(this._ftpUserID, this._ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.Default);
                string aa = readStream.ReadToEnd();
                if (aa == "") return false;
                return true;
            }
            catch
            {
                return false;
            }
        }

        //删除ftp文件
        public bool DeleteFtp(string fpath)
        {
            Regex re = new Regex(_httpDomain);
            fpath = re.Replace(fpath, "ftp://" + _ftpServerIP, 1);
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(fpath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                WebResponse response = reqFTP.GetResponse();
                return true;
            }
            catch
            {
                return false;
            }
        }

        //删除本地文件
        public void DeleteLocal(string fileName)
        {
            if (File.Exists(fileName))
                File.Delete(fileName);
        }

        //获取文件的全路径(如果是根目录则会出现问题)
        public string GetFileFullName(string directory, string controlPath, string extendName, bool isWeb)
        {
            string url = "";
            string month = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
            if (isWeb)
            {
                if (string.IsNullOrEmpty(controlPath))
                {
                    url = String.Format(directory + "/{0}/{1}", DateTime.Now.ToString("yyyyMMddhhmmssfff") + RandomUtil.CreateRandom(3), extendName);
                }

            }

            return "ftp://" + _ftpServerIP + url;
        }

        //保存到ftp服务器上
        public string SaveFtp(Stream stream, string fileName)
        {
            string uripath = fileName.Remove(fileName.LastIndexOf('/'));
            string url = "";
            if (!IsDir(uripath)) CreateDirectoryFtp(uripath);
            //if (!IsDir(this._ftpuri)) CreateDir(this._ftpuri);

            // 根据uri创建FtpWebRequest对象 
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(fileName));

            // ftp用户名和密码 
            reqFTP.Credentials = new NetworkCredential(this._ftpUserID, this._ftpPassword);

            // 默认为true,连接不会被关闭 
            // 在一个命令之后被执行 
            reqFTP.KeepAlive = false;

            // 指定执行什么命令 
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 指定数据传输类型 
            reqFTP.UseBinary = true;

            // 上传文件时通知服务器文件的大小 
            reqFTP.ContentLength = stream.Length;

            // 缓冲大小设置为2kb 
            int buffLength = 1024;
            byte[] buff = new byte[buffLength];
            int contentLen;

            try
            {
                // 把上传的文件写入流 
                Stream strm = reqFTP.GetRequestStream();

                // 每次读文件流的1kb                 
                contentLen = stream.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream 
                    strm.Write(buff, 0, contentLen);
                    contentLen = stream.Read(buff, 0, buffLength);
                }
                stream.Close();
                strm.Close();
                url = fileName.Replace(String.Format("ftp://{0}", this._ftpServerIP), _httpDomain);
            }
            catch
            {
                url = String.Empty;
            }
            return url;
        }
        public Stream LoadFtp(string filePath)
        {
            //FileStream fs = null;
            Stream responseStream = null;
            filePath = filePath.Replace(_httpDomain, "ftp://" + _ftpServerIP);
            try
            {
                //创建一个与FTP服务器联系的FtpWebRequest对象
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(filePath);
                //设置请求的方法是FTP文件下载
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                //连接登录FTP服务器
                request.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);

                //获取一个请求响应对象
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //获取请求的响应流
                responseStream = response.GetResponseStream();
            }
            catch (Exception e)
            {
                responseStream = null;
            }
            return responseStream;
        }
        public void LoadFtp(string filePath, string fileName)
        {
            FileStream fs = null;
            Stream responseStream = null;
            filePath = filePath.Replace(_httpDomain, "ftp://" + _ftpServerIP);
            try
            {
                //创建一个与FTP服务器联系的FtpWebRequest对象
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(filePath);
                //设置请求的方法是FTP文件下载
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                //连接登录FTP服务器
                request.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);

                //获取一个请求响应对象
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //获取请求的响应流
                responseStream = response.GetResponseStream();

                //判断本地文件是否存在,如果存在,则打开和重写本地文件
                if (File.Exists(fileName))
                {
                    fs = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite);
                }
                //判断本地文件是否存在,如果不存在,则创建本地文件
                else
                {
                    CreateDirectoryLocal(Path.GetDirectoryName(fileName));
                    fs = File.Create(fileName);
                }

                if (fs != null)
                {

                    int buffer_count = 1024;
                    byte[] buffer = new byte[buffer_count];
                    int size = 0;
                    while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
                    {
                        fs.Write(buffer, 0, size);
                    }
                    fs.Flush();
                    fs.Close();
                    responseStream.Close();
                }
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (responseStream != null)
                    responseStream.Close();
            }

        }
        //保存到本地
        public string SaveLocal(Stream stream, string fileName)
        {
            string url = "";
            try
            {
                CreateDirectoryLocal(Path.GetDirectoryName(fileName));
                using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    byte[] buffer = new byte[1024 * 10];
                    int contentLength = stream.Read(buffer, 0, buffer.Length);
                    while (contentLength != 0)
                    {
                        fileStream.Write(buffer, 0, contentLength);
                        contentLength = stream.Read(buffer, 0, buffer.Length);
                    }
                    stream.Close();
                    fileStream.Close();
                    url = fileName;
                }
            }
            catch (Exception)
            {

                url = string.Empty;
            }
            return url;

        }
        //UE S
        //获取文件的全路径(如果是根目录则会出现问题)
        public string GetFileFullNameUE(string directory, string controlPath, string extendName, bool isWeb)
        {
            string url = "";
            string realname = System.Guid.NewGuid().ToString();
            if (isWeb)
            {
                if (string.IsNullOrEmpty(controlPath))
                {
                    url = String.Format(directory + "/{0}{1}", realname, extendName);
                }
                else
                {
                    url = String.Format(directory + "/{0}/{1}{2}", controlPath, realname, extendName);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(controlPath))
                {
                    url = String.Format(directory + "\\{0}\\{1}{2}", realname, DateTime.Now.ToString("yyyyMMddhhmmssfff"), extendName);
                }
                else
                {
                    url = String.Format(directory + "\\{0}\\{1}\\{2}{3}", controlPath, realname, DateTime.Now.ToString("yyyyMMddhhmmssfff"), extendName);
                }
            }
            return url;
        }
        //UE E
    }
    public sealed class RandomUtil
    {
        /// <summary>
        /// 生成可变长[0-9]随机数
        /// </summary>
        /// <param name="length">随机数的长度[默认6位]</param>
        /// <returns>返回随机数字符串</returns>
        public static string CreateRandom(int length = 6)
        {
            Random rd = new Random();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                int num = rd.Next(0, 10);
                sb.Append(num);
            }
            return sb.ToString();
        }
    }
}

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Header{
    <link href="@Url.Content("~/Scripts/uploadify-v3.1/uploadify.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.8.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/uploadify-v3.1/jquery.uploadify-3.1.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $('#file_upload').uploadify({
                'buttonText': '上传文件',
                'swf': '@Url.Content("~/Scripts/uploadify-v3.1/uploadify.swf")',
                'uploader': '/Home/Upload',
                'fileSizeLimit': '204800kb',
                'width': 90,
                'height': 23,
                'onUploadSuccess': function (file, data, response) {
                    eval("data=" + data);
                    alert('文件 ' + file.name + ' 已经上传成功,并返回 ' + response + ' 保存文件名称为 ' + data.SaveName);
                }
            });
        });
    </script>
    <style type="text/css">
        body {
            font-size: 12px;
        }

        .tip {
            height: 20px;
            border-bottom: 1px solid #CCC;
            margin-bottom: 10px;
        }
    </style>
}
<div class="tip">
    jQuey Uploadify上传文件示例:
</div>
<div>
    <input type="file" id="file_upload" name="file_upload" />
</div>

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    @RenderSection("Header",false)
</head>

<body>
    @RenderBody()
</body>
</html>

Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ftpip" value="192.168.27.42"/>
    <add key="ftpuser" value="anonymous"/>
    <add key="ftppass" value=""/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime  maxRequestLength="2147483647" targetFramework="4.5" />

  </system.web>
  <system.webServer>
      <security>
          <requestFiltering>
              <requestLimits maxAllowedContentLength="2147483648"/>
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

Uploadify示例二

ResourceController.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UploadifyTest.Controllers
{
    public class ResourceController : Controller
    {

        public ActionResult Upload(HttpPostedFileBase uploadedFile)
        {
            if (uploadedFile.ContentLength == 0) 
                return new EmptyResult();

            string savedFileName = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), uploadedFile.FileName);
            uploadedFile.SaveAs(savedFileName);

            return new EmptyResult();
        }

        public ActionResult Index()
        {
            return View();
        }
    }
}

Index.cshtml

@{
    ViewBag.Title = "Index Page";
}

<!DOCTYPE html>

<html >
<head runat="server">
    <title>Index</title>
     <link href="<%= Url.Content("~/Content/site.css") %>" rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Scripts/jquery.uploadify-v2.1.4/uploadify.css") %>" rel="stylesheet" type="text/css" /> 
    <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script> 
    <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.uploadify-v2.1.4/swfobject.js") %>"></script> 
    <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.uploadify-v2.1.4/jquery.uploadify.v2.1.4.js") %>"></script> 
    <script type="text/javascript">
        $(document).ready(function () {

            $("#fileInput1").uploadify({
                'uploader': '<%= Url.Content("~/Scripts/jquery.uploadify-v2.1.4/uploadify.swf")%>',
                'script': '<%= Url.Content("~/Resource/Upload") %>',
                'auto': false,
                'multi': false,
                'expressInstall': '<%= Url.Content("~/Scripts/jquery.uploadify-v2.1.4/expressInstall.swf")%>',
                'cancelImg': '<%= Url.Content("~/Scripts/jquery.uploadify-v2.1.4/cancel.png") %>',
                'scriptAccess': 'always',
                'hideButton': false,
                'fileDesc': 'jpeg files (*.jpg)',
                'fileExt': '*.jpg',
                'fileDataName': 'uploadedFile',
                'sizeLimit': 1000000000,
                'onError': function (event, ID, fileObj, errorObj) {
                    alert("name: " + fileObj.name + " error type: " + errorObj.type + ", info: " + errorObj.info);
                },
                'onAllComplete': function (event, data) {
                    alert("allcomplete => " + data.filesUploaded + ":" + data.errors + ":" + data.allBytesLoaded + ":" + data.speed);
                },
                'onCheck': function () {
                    alert("oncheck");
                },
                'onComplete': function (event, id, fileObj, response, data) {
                    alert("oncomplete => " + ":" + fileObj.name + ":" + fileObj.filePath + ":" + fileObj.size + ":" + response);
                },
                'onOpen': function (event, id, fileObj) {
                    alert("onopen => " + ":" + fileObj.name + ":" + fileObj.filePath + ":" + fileObj.size);
                },
                'onProgress': function (event, id, fileObj, data) {
                    alert("onprogress => " + ":" + fileObj.name + ":" + fileObj.filePath + ":" + fileObj.size + ":" + data.percentage + ":" + data.bytesLoaded + ":" + data.allBytesLoaded + ":" + data.speed);
                }
            });
        });
    </script>

</head>
<body>   
    <div id="InterestingDiv">
        <p align="center">
            <input id="fileInput1" name="fileInput1" type="file" />
            <a href="javascript:$('#fileInput1').uploadifyUpload();">Upload Files</a></p>
    </div>

</body>
</html>

Uploadify示例三

NewsController.cs

using System;
using System.IO;
using System.Web.Mvc;
using UploadifyDemo.Models;

namespace UploadifyDemo.Controllers
{
    public class NewsController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(News model)
            {
            return View("NewsDisplay", model);
            }

        public ActionResult Upload()
            {
            var file = Request.Files["Filedata"];
            string extension = Path.GetExtension(file.FileName);
            string fileid = Guid.NewGuid().ToString();
            fileid = Path.ChangeExtension(fileid, extension);

            string savePath = Server.MapPath(@"~\Uploads\" + fileid);
            file.SaveAs(savePath);

            return Content(Url.Content(@"~\Uploads\" + fileid));
            }
    }
}

News.cs

using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Mvc;

namespace UploadifyDemo.Models
    {
    public class News
        {
        [Key]
        public int NewsID { get; set; }
        public string Title { get; set; }
        [AllowHtml]
        public string Content { get; set; }
        public HttpPostedFileBase Image { get; set; }
        }
    }

Index.cshtml

@model UploadifyDemo.Models.News
@{
    ViewBag.Title = "Index";
}
<link href="~/Scripts/Uploadify/uploadify.css" rel="stylesheet" />
<script src="~/Scripts/Uploadify/jquery.uploadify.min.js"></script>
<script src="~/Scripts/Tinymce/tinymce.min.js"></script>
<script>
    tinymce.init({
        selector: '#Content',
        height: 500,
        theme: 'modern',
        plugins: [
          'advlist autolink lists link image charmap print preview hr anchor pagebreak',
          'searchreplace wordcount visualblocks visualchars code fullscreen',
          'insertdatetime media nonbreaking save table contextmenu directionality',
          'emoticons template paste textcolor colorpicker textpattern imagetools'
        ],
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons ',
        image_advtab: true,


    });
</script>

<script type="text/javascript">
    $(function () {

        $('#file_upload').uploadify({

            'swf': '/Scripts/Uploadify/uploadify.swf',
            'uploader': "@Url.Action("Upload", "News")",
            'cancelImg': "@Url.Content("/Scripts/Uploadify/uploadify-cancel.png")",
            'fileSizeLimit': '1MB', // 添加 Kb, MB, GB
            'buttonText': '图片上传...', //按钮的文字
            'queueSizeLimit': 10, // 允许的最大文件数量
            'fileTypeDesc': 'Image Files',
            'fileTypeExts': '*.gif; *.jpg; *.png', //文件类型允许
            'onUploadSuccess': function (file, data, response) {
                tinyMCE.activeEditor.execCommand("mceInsertContent", true, "<img src='" + data + "' alt='Uploaded Image' class='img-responsive' />");
            }

        })

    }
);
</script>

<div class="panel panel-primary">
    <div class="panel-heading panel-head">添加新闻</div>
    <div class="panel-body">
        @using (Html.BeginForm("Index", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <div class="form-horizontal">
                <div class="form-group">
                    @Html.LabelFor(model => model.Title, new { @class = "col-lg-2 control-label" })
                    <div class="col-lg-9">
                        @Html.TextBoxFor(model => model.Title, new { @class = "form-control" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.Image, new { @class = "col-lg-2 control-label" })
                    <div class="col-lg-9">
                        <input type="file" name="Img" id="file_upload" />
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.Content, new { @class = "col-lg-2 control-label" })
                    <div class="col-lg-9">
                        @Html.TextAreaFor(model => model.Content, new { @class = "form-control", @row = 5 })
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-9"></div>
                    <div class="col-lg-3">
                        <button class="btn btn-success" id="btnSubmit" type="submit">
                            提交
                        </button>
                    </div>
                </div>
            </div>
        }
    </div>
</div>

NewsDisplay.cshtml

@model UploadifyDemo.Models.News
@{
    ViewBag.Title = "News Display";
}
<h2>新闻显示 - 查看已提交的内容</h2>
<div class="panel panel-primary">
    <div class="panel-heading panel-head">显示</div>
    <div class="panel-body">
        <div class="form-horizontal">
            <div class="form-group">
                @Html.LabelFor(model => model.Title, new { @class = "col-lg-2 control-label" })
                <div class="col-lg-9">
                    @Html.DisplayFor(model => model.Title, new { @class = "form-control" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Content, new { @class = "col-lg-2 control-label" })
                <div class="col-lg-9">
                    @Html.Raw(Model.Content)
                </div>
            </div>
        </div>
    </div>
</div>

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("News", "Index", "News")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @RenderSection("scripts", required: false)
</body>
</html>

BundleConfig.cs

using System.Web;
using System.Web.Optimization;

namespace UploadifyDemo
{
    public class BundleConfig
    {

        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));


            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

运行如图:

这里写图片描述


这里写图片描述

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值