前段時間,一直有練習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 GOSource 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 GOSource 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 API》http://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
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
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博客上也有相似或是相關的功能......