基于Layui + .net mvc文件上传

html

<div>
    <table width="100%">
        <tr>
            <td>
                <button type="button" class="layui-btn layui-btn-sm" id="附件上传">附件上传</button>
            </td>
        </tr>
    </table>
</div>

js

/*文件上传方法*/
layui.use('upload', function () {
    var $ = layui.jquery
        , upload = layui.upload
        , form = layui.form;
    upload.render({
        elem: '#附件上传'//附件上传按钮ID
        , url: '/tool/upload(附件上传后台地址)'
        , multiple: true
        , accept: 'file'
        , exts: 'zip|rar|7z|doc|docx|ppt|pptx|txt|pdf'//允许的类别
        , before: function (obj) {/*上传前执行的部分*/ }
        , done: function (res) {/*上传后执行的部分*/ }
        , allDone: function (res) {/*全部文件上传完毕执行该方法*/ }
    });
});

Controller

using System;
using System.Web.Mvc;

namespace SFMVC3._0.Controllers
{
    public class toolsController : Controller
    {
        /// <summary>
        /// 文件上传方法
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        public string upload(FormCollection fc)
        {
            try
            {
                string guid = Guid.NewGuid().ToString();
                var file = Request.Files[0];
                if (file == null ||
                  String.IsNullOrEmpty(file.FileName) ||
                  file.ContentLength == 0)
                {
                    return "{"code":1,"msg":"文件上传失败!" ,"data":{"src":""}}";
                }

                string filename = System.IO.Path.GetFileName(file.FileName);
                string newName = buildFileName(guid, filename);
                string virtualPath = String.Format("/upload/{0}", newName);

                string path = Server.MapPath(virtualPath);
                file.SaveAs(path);                

                return "{"code":0,"msg":"文件上传成功!" ,"data":{"src":"","filename":"" + filename + "","newname":"" + newName + "","size":"" + (file.ContentLength/1024) + ""}}";
            }
            catch (Exception ex)
            {
                return "{"code":1,"msg":"文件上传失败!" ,"data":{"src":""}}";
            }
        }

        /// <summary>
        /// 根据文件名称生产新的文件名称;
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string buildFileName(string newname, string filename)
        {
            string postfix = filename.Substring(filename.LastIndexOf('.'));
            string newName = newname + postfix;

            return newName;
        }
    }
}

 

你可能感兴趣的