Web API与文件操作

前段时间,一直有练习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博客上也有相似或是相关的功能......

时间: 2024-07-29 01:53:07

Web API与文件操作的相关文章

ASP.NET Core Web API Cassandra CRUD 操作

在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将使用 Postman 来完成. ASP.NET Core 是 ASP.NET 的重大的重构,ASP.NET Core 是一个全新的开源和跨平台的框架,用于构建如 Web 应用.物联网(IoT)应用和移动后端应用等连接到互联网的基于云的现代应用程序. ASP.NET Core 已经内置了用 MVC 架

使用 Swagger UI 与 Swashbuckle 创建 RESTful Web API 帮助文件

作者:Sreekanth Mothukuru 2016年2月18日 本文旨在介绍如何使用常用的 Swagger 和 Swashbuckle 框架创建描述 Restful API 的交互界面,并为 API 用户提供丰富的探索.文件和操作体验. 源代码: 下载 SwaggerUi_2.zip 步骤 在本文中,我们将在 Asp.Net 创建一个简单的 Restful API,并整合 Swashbuckle 和 Swagger UI.本文分为三部分. 创建 Asp.Net Web API项目 通过实体数

Xamarin.Forms学习之Platform-specific API和文件操作

这篇文章的分享原由是由于上篇关于Properties的保存不了,调用SavePropertiesAsync()方法也不行,所以我希望通过操作文件的方式保存我的需要的数据,然后我看了一下电子书中的第二十章和需要相关知识的第九章,这篇文章中的内容则是我学习这两章的一点记录和分享,还是那样,有错请留言指正,谢谢! 不同的平台存在着一些特定的API,通过在电子书中两章的学习,实践一下如何调用这些API和将这些API封装成公共的库,供以后的项目调用.以一个显示平台信息的小实例开始做一个简单的演示,其运行效

ASP.NET(C#) Web Api通过文件流下载文件到本地实例

下载文件到本地是很多项目开发中需要实现的一个很简单的功能.说简单,是从具体的代码实现上来说的,.NET的文件下载方式有很多种,本示例给大家介绍的是ASP.NET Web Api方式返回HttpResponseMessage下载文件到本地.实现的方法很简单,其中就是读取服务器的指定路径文件流,将其做为返回的HttpResponseMessage的Content.直接贴出DownloadController控件器的代码: using System; using System.Collections.

【API】文件操作编程-CreateFile、WriteFile、SetFilePointer

1.说明 很多黑客工具的实现是通过对文件进行读写操作的,而文件读写操作实质也是对API函数的调用. 2.相关函数 CreateFile : 创建或打开文件或I/O设备.最常用的I/O设备如下:文件,文件流,目录,物理磁盘卷,控制台缓冲,磁带驱动器,通信资源,邮槽,和管.函数返回一个句柄,可以根据文件或设备和指定的标志和属性来访问各种类型的I/O文件或设备. HANDLE WINAPI CreateFile( _In_ LPCTSTR lpFileName, _In_ DWORD dwDesire

Web API 2 的操作结果

这是msdn原文文档!明天用,留存. Web API 控制器操作可以返回以下任何内容: void HttpResponseMessage IHttpActionResult 其他类型 根据返回的这种情况,Web API 将使用不同的机制来创建 HTTP 响应. 返回类型Web API 如何创建响应 void  返回空的204(无内容) HttpResponseMessage 直接转换为 HTTP 响应消息. IHttpActionResult 调用ExecuteAsync创建HttpRespon

Windows API——SHFileOperation——文件操作

1 int SHFileOperation( LPSHFILEOPSTRUCT lpFileOp); 如果执行成功返回0. typedef struct _SHFILEOPSTRUCT { HWND hwnd; //指向发送消息的窗口 UINT wFunc; //执行的操作 LPCTSTR pFrom; //源文件名 LPCTSTR pTo; //目标文件名 FILEOP_FLAGS fFlags; //操作与确认标识 BOOL fAnyOperationsAborted; //操作是否终止 L

Asp.Net Web Api 2 实现多文件打包并下载文件示例源码_转

一篇关于Asp.Net Web Api下载文件的文章,之前我也写过类似的文章,请见:<ASP.NET(C#) Web Api通过文件流下载文件到本地实例>本文以这篇文章的基础,提供了ByteArrayContent的下载以及在下载多个文件时实现在服务器对多文件进行压缩打包后下载的功能.关于本文中实现的在服务器端用.NET压缩打包文件功能的过程中,使用到了一个第方类库:DotNetZip,具体的使用将在正文中涉及.好了,描述了这么多前言,下面我们进入本文示例的正文. 一.创建项目 1.1 首先创

通过HttpClient 调用ASP.NET Web API

在前面两篇文章中我们介绍了ASP.NET Web API的基本知识和原理,并且通过简单的实例了解了它的基本(CRUD)操作.我们是通过JQuery和Ajax对Web API进行数据操作.这一篇我们来介绍一下使用HttpClient的方式来对Web API进行数据操作. 这里我们还是继续使用对Product的操作实例来演示一下它的基本应用. 创建ASP.NET Web API应用程序  在VS中选择创建一个ASP.NET Web Application应用程序,在向导的下一个窗口中选择Web AP