Web API與文件操作

来源:http://www.cnblogs.com/insus/archive/2016/07/30/5714440.html
-Advertisement-
Play Games

前段時間,一直有練習ASP.NET MVC與Web API交互,接下來,Insus.NET再做一些相關的練習,Web API與文件操作,如POST文件至Web API,更新或是刪除等。不管怎樣,先在資料庫創建一張表,用來存儲上傳的文件。本實例中是把文件存儲過資料庫的。 CREATE TABLE Ap ...


前段時間,一直有練習ASP.NET MVC與Web API交互,接下來,Insus.NET再做一些相關的練習,Web API與文件操作,如POST文件至Web API,更新或是刪除等。

不管怎樣,先在資料庫創建一張表,用來存儲上傳的文件。本實例中是把文件存儲過資料庫的。



CREATE TABLE ApiFileDemo
(
    [Afd_nbr] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    [Picture] [image] NULL,
    [PictureType] [nvarchar](30) NULL,
    [FileExtension] [nvarchar](10) NULL
)
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Insert]
(    
    @Picture IMAGE,
    @PictureType NVARCHAR(30),
    @FileExtension NVARCHAR(10)
)
AS
INSERT INTO [dbo].[ApiFileDemo] ([Picture],[PictureType],[FileExtension]) VALUES (@Picture,@PictureType,@FileExtension)
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Update]
(
    @Afd_nbr INT,
    @Picture IMAGE,
    @PictureType NVARCHAR(30),
    @FileExtension NVARCHAR(10)
)
AS
UPDATE [dbo].[ApiFileDemo]  SET [Picture] = @Picture,[PictureType] = @PictureType,[FileExtension] = @FileExtension WHERE [Afd_nbr] = @Afd_nbr
GO

CREATE PROCEDURE [dbo].[usp_ApiFileDemo_Delte]
(
    @Afd_nbr INT
)
AS
DELETE FROM [dbo].[ApiFileDemo] WHERE [Afd_nbr] = @Afd_nbr
GO
Source Code


寫到這裡,發現少了一個存儲過程,就是獲取某一張圖片的:


CREATE PROCEDURE [dbo].[usp_ApiFileDemo_GetByPrimarykey]
(
    @Afd_nbr INT
)
AS
SELECT [Afd_nbr],[Picture],[PictureType],[FileExtension] FROM [dbo].[ApiFileDemo] WHERE [Afd_nbr] = @Afd_nbr
GO
Source Code

 
接下來,我們可以設計Web API介面,待完成了,發佈至網上,其它客戶端就可以操作了。

根據資料庫表,可以在API項目中,創建Model:


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

namespace Insus.NET.Models
{
    public class File
    {
        public int Afd_nbr { get; set; }

        public byte[] Picture { get; set; }

        public string PictureType { get; set; }

        public string FileExtension { get; set; }
    }
}
Source Code


寫好model之後,還需要為API寫一個實體,這個對象只是讓程式與資料庫進行交互。獲取與存儲等操作:


using Insus.NET.DataBases;
using Insus.NET.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Insus.NET;

namespace Insus.NET.Entities
{
    public class FileEntity
    {
        BizSP sp = new BizSP();
        public DataTable GetFileByPrimarykey(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_GetByPrimarykey";
            return sp.ExecuteDataSet().Tables[0];
        }

        public void Insert(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Picture", SqlDbType.Image,-1,f.Picture),
                                    new Parameter("@PictureType",SqlDbType.NVarChar,-1,f.PictureType),
                                    new Parameter("@FileExtension",SqlDbType.NVarChar,-1,f.FileExtension)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Insert";
            sp.Execute();
        }

        public void Update(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr),
                                    new Parameter("@Picture", SqlDbType.Image,-1,f.Picture),
                                    new Parameter("@PictureType",SqlDbType.NVarChar,-1,f.PictureType),
                                    new Parameter("@FileExtension",SqlDbType.NVarChar,-1,f.FileExtension)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Update";
            sp.Execute();
        }

        public void Delete(File f)
        {
            List<Parameter> param = new List<Parameter>() {
                                    new Parameter("@Afd_nbr", SqlDbType.Int,4,f.Afd_nbr)
            };
            sp.ConnectionString = DB.ConnectionString;
            sp.Parameters = param;
            sp.ProcedureName = "usp_ApiFileDemo_Delte";
            sp.Execute();
        }
    }
}
Source Code

 

下麵的控制器FileController,即是為客戶端訪問的介面,這個類別,它是繼承了ApiController。

 

using Insus.NET.Entities;
using Insus.NET.ExtendMethods;
using Insus.NET.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Insus.NET.Controllers
{
    public class FileController : ApiController
    {
        // GET: File
        FileEntity fe = new FileEntity();

        // GET: ApiFileDemo

        [HttpGet]
        public string Get(int id)
        {
            File f = new File();
            f.Afd_nbr = id;
            return fe.GetFileByPrimarykey(f).ToJson();
        }

        [HttpPost]
        public void Post(File f)
        {
            fe.Insert(f);
        }

        [HttpPut]
        public void Put(File f)
        {
            fe.Update(f);
        }

        [HttpDelete]
        public void Delete(File f)
        {
            fe.Delete(f);
        }

        [HttpDelete]
        public void Delete(int id)
        {
            File f = new File();
            f.Afd_nbr = id;
            fe.Delete(f);
        }
    }
}
Source Code

 
Web API完成,我們需要把它發佈至IIS中去,如何發佈,可以參考《創建與使用Web APIhttp://www.cnblogs.com/insus/p/5019088.html......


Ok,接下來,我們開發客戶端的程式,嘗試上Web API上傳一些文件。

在客戶端的項目中,創建一個mode:


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

namespace Insus.NET.Models
{
    public class File
    {
        public int Afd_nbr { get; set; }

        public byte[] Picture { get; set; }

        public string PictureType { get; set; }

        public string FileExtension { get; set; }
    }
}
Source Code

 

ASP.NET MVC的控制器中,創建2個Action:

 

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

        [HttpPost]
        public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {
                    Insus.NET.Models.File f = new Insus.NET.Models.File();
                    f.PictureType = file.ContentType;
                    string fn = Path.GetFileName(file.FileName);
                    f.FileExtension = fn.Substring(fn.LastIndexOf('.'));
                    using (Stream inputStream = file.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        f.Picture = memoryStream.ToArray();
                    }
                    HttpClient client = new HttpClient();
                    string ff = f.ToJson();
                    HttpContent httpcontent = new StringContent(ff, System.Text.Encoding.UTF8, "application/json");
                    client.PostAsync("http://localhost:9001/api/file", httpcontent)
                        .ContinueWith((postTask) =>
                        {
                            postTask.Result.EnsureSuccessStatusCode();
                        });
                }
            }
            return RedirectToAction("Upload");
        }
Source Code

 

在視圖中,可以這樣做:

 

程式運行:


 

 圖片上傳成功之後,現在我們需要把圖片顯示出來。
由於存儲的是二進位的數據流,顯示圖片時,需要處理一下,需要寫一個自定義的Result,如:PictureResult,它需要繼承ContentResult:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Insus.NET.Results
{
    public class PictureResult : ContentResult
    {
        public byte[] _Picture { get; set; }
        public string _PictureType { get; set; }

        public PictureResult(byte[] sourceStream, String contentType)
        {
            _Picture = sourceStream;
            _PictureType = contentType;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = ContentType;

            if (_Picture != null)
            {
                var stream = new MemoryStream(_Picture);
                stream.WriteTo(response.OutputStream);
                stream.Dispose();
            }
        }
    }
}
Source Code


接下來,我們在控制器創建視圖的Action:

 

 public ActionResult ShowPhoto()
        {
            return View();
        }
        
        public ActionResult ShowPicture(int id)
        {
            var files = ApiUtility.Get<Insus.NET.Models.File>("http://localhost:9001/api/file/" + id);
            var model = files.FirstOrDefault();

            PictureResult pictureResult = new PictureResult(model.Picture, model.PictureType);
            return pictureResult;
        }
Source Code

 
客戶端程式運行,可以看到圖片顯示的效果:


在Web API的介面還有更新,刪除的介面,看官們可以繼續完成。方法在Insus.NET博客上也有相似或是相關的功能......

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文介紹的是如何使用C#訪問由IIS搭建的http文件伺服器,訪問包括:下載、上傳、刪除及列出文件(或目錄) ...
  • 今天在做一個小網站的時候遇到很多問題唉,我還是個菜鳥,懂的也不多,今天一個表單的提交按鈕用不了,都弄了幾個小時唉。不過最後還是搞定了,還有瀏覽器有開發人員選項,不然我都不知道我還要繼續排查多久哦,今天晚上在把數據存入資料庫的又出現了問題。我使用的是Entity Framework的Code Firs ...
  • 【本人原創】,歡迎交流和分形技術,轉載請附上如下內容: 作者:itshare 【轉自】http://www.cnblogs.com/itshare/ 1. 實驗目的: 使用線程池的時候,有時候需要考慮伺服器的最大線程數目和程式最快執行所有業務邏輯的取捨。並非邏輯線程越多也好,而且新的邏輯線程必須會在 ...
  • 一、FileStream的基礎知識 屬性: CanRead 判斷當前流是否支持讀取,返回bool值,True表示可以讀取 CanWrite 判斷當前流是否支持寫入,返回bool值,True表示可以寫入 方法: Read() 從流中讀取數據,返回位元組數組 Write() 將位元組塊(位元組數組)寫入該流 ...
  • 1 /// <summary> 2 /// 九宮格演算法 3 /// </summary> 4 public void NineTable() 5 { 6 //創建一個三階方陣 7 int[,] arr = new int[3, 3]; 8 //第3行的行下標 9 int a = 2; 10 //第2 ...
  • 說明:本文是個人翻譯文章,由於個人水平有限,有不對的地方請大家幫忙更正。 原文: "dotnet run" 翻譯: "dotnet run" 名稱 dotnet run 沒有任何明確的編譯或啟動命令運行“就地”(即運行命令的目錄)源代碼。 概要 `dotnet run [ framework] [ ...
  • 發現很少有集中討論C#可變性限制的中文博文(要麼就是一大段文字中夾雜很多凌亂的部分),所以寫發篇博文,集中討論,這些限制基本是基於安全考慮,亦或者根本難以實現而產生的。 註:本文不再解釋什麼是可變性,以及本文所討論的問題都基於.NET 4至.NET 4.5。所有地方我都力求簡潔。 好了,廢話不說了, ...
  • 隨著互聯網項目用戶訪問量不斷上升,單點web伺服器是無法滿足大型高併發高負載的業務處理的,為了給web伺服器做負載均衡方案,打算採用Nginx搭建負載均衡伺服器,把用戶請求分配到N個伺服器來緩解伺服器壓力。 Nginx簡介: Nginx (“engine x”) 是一個高性能的 HTTP 和 反向代 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...