.Net Core圖片上傳,將上傳圖片轉化為byte[]類型保存到數據庫中


一、數據上傳(將圖片信息上傳至數據庫)

這里那我是用的EFcore連接的數據庫。數據庫的名稱為test,字段為

 

 

前端

主要是數據的傳輸這塊需要注意,data分兩塊發送一個發送上傳文件,一個發送其他的信息

@{
    ViewData["Title"] = "Home Page";

}
<script src="~/jquery/jquery.min.js"></script>
<div>添加數據</div>
<div>
    <form id="from-upFile" name="form" method="post" enctype="multipart/form-data">

        <input type="text" id="name" name="Name" />
        <br />
        <input type="file" id="file" name="Image" />
        <br />
        <input type="button" value="添加" onclick="a()" />
        </form>
        <script>
            function a() {
                var name = $("#name").val();
                $.ajax({
                    url: "/Home/StudentAdd", 
                    //data: new FormData(document.getElementById("from-upFile")),
                    data: { "Name": name},
                    data: new FormData(document.getElementById("from-upFile")),
                    // 告訴jQuery不要去處理發送的數據,用於對data參數進行序列化處理 這里必須false
                    processData: false,
                    // 告訴jQuery不要去設置Content-Type請求頭
                    contentType: false,
                    type: "post",
                    dataType: "json",
                    success: function (json) {
                        console.log(json);
                    },
                    error: function (json) {
                    }
                });
            }
        </script>
</div>

  

后端接收

Request.Form.Files[0]這塊那我是通過打斷點的方式,知道他的類型為Formfile的

[HttpPost]
        public string StudentAdd(string Name)
        {
            //HttpContext.Request.Files[0];framework框架控制器獲取上傳文件
            //FileStream fs = HttpContext.Current.Request.Files[0]; //獲取上傳文件,framework框架api
            //IFormFileCollection files = Request.Form.Files;上傳的文件合集
            FormFile file = Request.Form.Files[0] as FormFile;//上傳文件
            
            Stream fs =file.OpenReadStream();//打開讀取上傳文件的請求流
            //將圖片轉化位byte[] 格式進行數據存儲
            BinaryReader br = new BinaryReader(fs);//將原始數據類型讀取為二進制的值
            byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //將流讀入到字節數組中
            StudentInfo s = new StudentInfo() { Name=Name,Image=imgBytesIn};
            using (TestDateBase db = new TestDateBase())
            {
                db.StudentInfos.Add(s);
                db.SaveChanges();
            }
            return "文件已上傳!";
        }

  

注意如果是framework框架的話,后台獲取上傳信息會有些不一樣的地方!

 

二、顯示數據(將數據庫image數據顯示在頁面之中)

方式一(razor頁面)頁面和后端在一個解決方案上

前端

@{
    ViewData["Title"] = "Home Page";

}
@model List<StudentInfo>
<script src="~/jquery/jquery.min.js"></script>
<div>數據顯示</div>
<div>
    
    <ul>
        @foreach (var item in Model)
        {
            <li><img src='@(item.Image!=null?"data:image/png;base64,"+Convert.ToBase64String(item.Image):"")' /></li>
        }
    </ul>
</div>

后端控制器

 

 

方式二(常用使用ajax獲取數據顯示在頁面之上)前后端分離的情況下

前端

<script src="~/jquery/jquery.min.js"></script>
<h2>數據顯示</h2>
<style>
    table {
        table-layout:fixed;
    }
    table, table tr {
        border-collapse:collapse;
    }
        table tr td {
            word-spacing:normal;
        }
</style>
<table id="StudentInfosTable" border="1" style="width:60%;min-width:500px;margin:0 auto">
    <tr>
        <td>姓名</td>
        <td>圖片</td>
    </tr>
</table>
<a href="#" id="btn">點擊查詢數據</a>
<div>
    <script>
        document.getElementById("btn").onclick = function () {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/Home/Privacy', true);
            xhr.responseType = "json"; //arraybuffer   blob
            //xhr.setRequestHeader("client_type", "DESKTOP_WEB");
            //xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.status == 200 && xhr.readyState == 4) {
                    var response = 'response' in xhr ? xhr.response : xhr.responseText;
                    //console.log(xhr.response instanceof Blob);

                    // 方法二
                    //var blob = new Blob([xhr.response], { type: "image/png" });//返回類型為 arraybuffer
                    //var imageUrl = (window.URL || window.webkitURL).createObjectURL(xhr.response);//返回類型為 blob
                    for (var i = 0; i < response.length; i++) {
                        $("#StudentInfosTable").append("<tr><td>" + response[i].name + "</td><td><img src='data:image/png;base64," + response[i].image + "' width='100'height='100' /></td></tr>");
                    }
                }
            };
            xhr.send();
        }
    </script>
</div>

  

API接口傳輸數據

 [HttpPost]
        public JsonResult Privacy()
        {
            TestDateBase db = new TestDateBase();
            var a = db.StudentInfos.ToList();
            //MemoryStream ms = new MemoryStream(b.last().Image);//在內存中操作圖片數據
            //Bitmap bmp = new Bitmap(Bitmap.FromStream(ms));
            return Json(a);
        }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM