1、bootstrap-upload

1、bootstrap-upload

前端代碼:css

@{
    Layout = null;
}

<!DOCTYPE html>

<html lang="zh-CN">
<head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">

    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>

    <link href="https://cdn.bootcss.com/bootstrap-fileinput/4.5.1/css/fileinput.min.css" rel="stylesheet">

    <script src="https://cdn.bootcss.com/bootstrap-fileinput/4.5.1/js/fileinput.min.js"></script>
    <link href="https://cdn.bootcss.com/bootstrap-fileinput/4.5.1/css/fileinput-rtl.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/font-awesome/5.10.0-11/css/all.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap-fileinput/4.5.1/img/loading-sm.gif">


</head>
<body>

    <div class="container">
        <h2>模態框實例</h2>
        <!-- 按鈕:用於打開模態框 -->
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
            打開模態框
        </button>

        <!-- 模態框 -->
        <div class="modal fade" id="myModal">
            <div class="modal-dialog">
                <div class="modal-content">

                    <!-- 模態框頭部 -->
                    <div class="modal-header">
                        <h4 class="modal-title">文 件 上 傳</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>

                    <!-- 模態框主體 -->
                    <div class="modal-body">

                        <div class="col-sm-12">
                            <input id="input-id" name="file" multiple type="file" data-show-caption="true">
                        </div>

                    </div>

                    <!-- 模態框底部 -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">關閉</button>
                    </div>

                </div>
            </div>
        </div>

    </div>

    <script>

        $(function () {
            initFileInput("input-id");
        })

        function initFileInput(ctrlName) {
            var control = $('#' + ctrlName);
            control.fileinput({
                language: 'zh', //設置語言
                uploadUrl: "/UploadPack/Uploadurl", //上傳的地址
                allowedFileExtensions: ['ipa', 'jpg', 'gif', 'png', 'doc', 'docx', 'pdf', 'ppt', 'pptx', 'txt'],//接收的文件後綴
                maxFilesNum: 5,//上傳最大的文件數量
                //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
                uploadAsync: true, //默認異步上傳
                showUpload: true, //是否顯示上傳按鈕
                showRemove: true, //顯示移除按鈕
                showPreview: true, //是否顯示預覽
                showCaption: false,//是否顯示標題
                browseClass: "btn btn-primary", //按鈕樣式
                //dropZoneEnabled: true,//是否顯示拖拽區域
                //minImageWidth: 50, //圖片的最小寬度
                //minImageHeight: 50,//圖片的最小高度
                //maxImageWidth: 1000,//圖片的最大寬度
                //maxImageHeight: 1000,//圖片的最大高度
                maxFileSize: 0,//單位爲kb,若是爲0表示不限制文件大小
                //minFileCount: 0,
                //maxFileCount: 10, //表示容許同時上傳的最大文件個數
                enctype: 'multipart/form-data',
                validateInitialCount: true,
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                msgFilesTooMany: "選擇上傳的文件數量({n}) 超過容許的最大數值{m}!",

            }).on('filepreupload', function (event, data, previewId, index) {     //上傳中
                console.log(data)
                var form = data.form, files = data.files, extra = data.extra,
                    response = data.response, reader = data.reader;
                console.log('文件正在上傳');
            }).on("fileuploaded", function (event, data, previewId, index) {    //一個文件上傳成功
                console.log('文件上傳成功!' + data.id);

            }).on('fileerror', function (event, data, msg) {  //一個文件上傳失敗
                console.log('文件上傳失敗!' + data.id);
            })
        }
    </script>

</body>
</html>

 

 

下面說明使用Core坑html

1、基於Core的獲取文件上傳

一、(List<IFormFile> files)

前端代碼:前端

後臺代碼:jquery

 

二、([FromForm(Name = "file")] List<IFormFile> files)

        [HttpPost]
        public async Task<IActionResult> Uploadurl([FromForm(Name = "file")] List<IFormFile> files) //上傳圖片
        {
            if (files.Count > 0)
            {
                string path = Path.Combine(Environment.CurrentDirectory, "Upload", DateTime.Now.ToString("yyyy-MM-dd"));
                if (!System.IO.Directory.Exists(path))//判斷上傳路徑是否存在
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                string filePath = string.Empty;
                string fileName = string.Empty;
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        string fileFormat = System.IO.Path.GetExtension(formFile.FileName);//獲取文件後綴格式
                        fileName = Guid.NewGuid().ToString("n") + fileFormat;
                        filePath = Path.Combine(path,fileName);//中間處理爲惟一格式文件
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            try
                            {
                                //保存文件
                                await formFile.CopyToAsync(stream);
                            }
                            catch (Exception ex)
                            {
                                return Json(new { Status = 1, Message = "保存失敗" });
                            }

                        }
                    }
                }
                return Json(new { Status = 1, Message = "保存成功" });
            }
            else
            {
                return Json(new { Status = 1, Message = "上傳文件爲空!" });
            }

        }

 

2、基於MVC的獲取文件上傳

        [HttpPost]
        public ActionResult Uploadurl(HttpPostedFileBase file) //上傳圖片
        {
            Basics basics = new Basics();

            if (basics.SaveFiles(file))
            {
                return Json(new { Status=1, Message = "保存成功"}, "text/html", JsonRequestBehavior.AllowGet);
            }
            else {
                return Json(new { Status = 1, Message = "保存失敗" }, "text/html", JsonRequestBehavior.AllowGet);
            }
        }

封裝方法bootstrap

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web; //

namespace Common
{
    public class Basics
    {
        public bool SaveFiles(HttpPostedFileBase file)
        {
            try
            {
                var Filename = file.FileName;
                string SavePath = "../Uploads/";
                string _Filename = DateTime.Now.ToString("yyyyMMddhhmmss") + Filename;
                //保存
                //Server.MapPath()的全名是System.Web.HttpContext.Current.Server.MapPath()
                file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(SavePath + _Filename));

            }catch
            {
                return false;
            }
            finally {
              
            }

            return true;

        }
    }
}
相關文章
相關標籤/搜索