Web API and file operations, webapi operations

Source: Internet
Author: User
Tags tojson

Web API and file operations, webapi operations

Some time ago, I have been practicing ASP. net mvc interacts with Web APIs. Next, Insus.. NET.

Create a table in the database to store uploaded files. In this example, files are stored in the database.



Create table ApiFileDemo ([Afd_nbr] int identity (1, 1) primary key not null, [Picture] [image] NULL, [PictureType] [nvarchar] (30) NULL, [FileExtension] [nvarchar] (10) NULL) gocreate procedure [dbo]. [usp_ApiFileDemo_Insert] (@ Picture IMAGE, @ PictureType NVARCHAR (30), @ FileExtension NVARCHAR (10) asinsert into [dbo]. [ApiFileDemo] ([Picture], [PictureType], [FileExtension]) VALUES (@ Picture, @ PictureType, @ FileExtension) gocreate procedure [dbo]. [usp_ApiFileDemo_Update] (@ Afd_nbr INT, @ Picture IMAGE, @ PictureType NVARCHAR (30), @ FileExtension NVARCHAR (10) ASUPDATE [dbo]. [ApiFileDemo] SET [Picture] = @ Picture, [PictureType] = @ PictureType, [FileExtension] = @ FileExtension WHERE [Afd_nbr] = @ Afd_nbrGOCREATE PROCEDURE [dbo]. [usp_ApiFileDemo_Delte] (@ Afd_nbr INT) asdelete from [dbo]. [ApiFileDemo] WHERE [Afd_nbr] = @ Afd_nbrGOSource Code


Here, we find that a stored procedure is missing, that is, getting an image:


Create procedure [dbo]. [usp_ApiFileDemo_GetByPrimarykey] (@ Afd_nbr INT) ASSELECT [Afd_nbr], [Picture], [PictureType], [FileExtension] FROM [dbo]. [ApiFileDemo] WHERE [Afd_nbr] = @ Afd_nbrGOSource Code

 
Next, we can design the Web API interface. After the interface is released to the Internet, other clients can perform the operation.

Based on the database table, you can create a Model in an API project:


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


After writing the model, you also need to write an entity for the API. This object only allows the program to interact with the database. Operations such as retrieval and storage:


Using Insus. NET. dataBases; using Insus. NET. models; 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

 

The following controller, FileController, is the interface accessed by the client. This class inherits from ApiController.

 

Using Insus. NET. entities; using Insus. NET. extendMethods; using Insus. NET. models; 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 is complete, we need to publish it to IIS, how to publish, you can refer to the "Create and use Web API" http://www.cnblogs.com/insus/p/5019088.html ......


OK. Next, we develop the client program and try to upload some files through the Web API.

In the client project, create a 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

 

In the controller of ASP. net mvc, create two actions:

 

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

 

In the view, you can do this:

 

Program running:


 

After the image is uploaded successfully, we need to display the image.
Because the binary data stream is stored, you need to handle the image display. You need to write a custom Result, such as PictureResult, which inherits 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 = sourceStr Eam; _ 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


Next, we create the view Action in the controller:

 

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

 
The client runs the program and you can see the image display effect:


There are also updated and deleted interfaces in the Web API interface. The viewer can continue to complete the operation. Methods have similar or related functions on the Insus. NET blog ......

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.