分享WebApi2 文件图片上传与下载功能实例
这篇文章主要介绍了WebApi2 文件图片上传与下载功能,需要的朋友可以参考下
Asp.Net Framework webapi2 文件上传与下载 前端界面采用Ajax的方式执行
一、项目结构
1.App_Start配置了跨域访问,以免请求时候因跨域问题不能提交。具体的跨域配置方式如下,了解的朋友请自行略过。
跨域配置:NewGet安装dll Microsofg.AspNet.Cors
然后在App_Start 文件夹下的WebApiConfig.cs中写入跨域配置代码。
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); // Web API configuration and services //跨域配置 //need reference from nuget config.EnableCors(new EnableCorsAttribute("*", "*", "*")); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //if config the global filter input there need not write the attributes //config.Filters.Add(new App.WebApi.Filters.ExceptionAttribute_DG()); } }
跨域就算完成了,请自行测试。
2.新建两个控制器,一个PicturesController.cs,一个FilesController.cs当然图片也是文件,这里图片和文件以不同的方式处理的,因为图片的方式文件上传没有成功,所以另寻他路,如果在座的有更好的方式,请不吝赐教!
二、项目代码
1.我们先说图片上传、下载控制器接口,这里其实没什么好说的,就一个Get获取文件,参数是文件全名;Post上传文件;直接上代码。
using QX_Frame.App.WebApi; using QX_Frame.FilesCenter.Helper; using QX_Frame.Helper_DG; using QX_Frame.Helper_DG.Extends; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web.Http; /** * author:qixiao * create:2017-5-26 16:54:46 * */ namespace QX_Frame.FilesCenter.Controllers { public class PicturesController : WebApiControllerBase { //Get : api/Pictures public HttpResponseMessage Get(string fileName) { HttpResponseMessage result = null; DirectoryInfo directoryInfo = new DirectoryInfo(IO_Helper_DG.RootPath_MVC + @"Files/Pictures"); FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault(); if (foundFileInfo != null) { FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(fs); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name; } else { result = new HttpResponseMessage(HttpStatusCode.NotFound); } return result; } //POST : api/Pictures public async Task<IHttpActionResult> Post() { if (!Request.Content.IsMimeMultipartContent()) { throw new Exception_DG("unsupported media type", 2005); } string root = IO_Helper_DG.RootPath_MVC; IO_Helper_DG.CreateDirectoryIfNotExist(root + "/temp"); var provider = new MultipartFormDataStreamProvider(root + "/temp"); // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); List<string> fileNameList = new List<string>(); StringBuilder sb = new StringBuilder(); long fileTotalSize = 0; int fileIndex = 1; // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { //new folder string newRoot = root + @"Files/Pictures"; IO_Helper_DG.CreateDirectoryIfNotExist(newRoot); if (File.Exists(file.LocalFileName)) { //new fileName string fileName = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); string newFileName = Guid.NewGuid() + "." + fileName.Split('.')[1]; string newFullFileName = newRoot + "/" + newFileName; fileNameList.Add($"Files/Pictures/{newFileName}"); FileInfo fileInfo = new FileInfo(file.LocalFileName); fileTotalSize += fileInfo.Length; sb.Append($" #{fileIndex} Uploaded file: {newFileName} ({ fileInfo.Length} bytes)"); fileIndex++; File.Move(file.LocalFileName, newFullFileName); Trace.WriteLine("1 file copied , filePath=" + newFullFileName); } } return Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($"{fileNameList.Count} file(s) /{fileTotalSize} bytes uploaded successfully! Details -> {sb.ToString()}", fileNameList, fileNameList.Count)); } } }
里面可能有部分代码在Helper帮助类里面写的,其实也仅仅是获取服务器根路径和如果判断文件夹不存在则创建目录,这两个代码的实现如下:
public static string RootPath_MVC { get { return System.Web.HttpContext.Current.Server.MapPath("~"); } } //create Directory public static bool CreateDirectoryIfNotExist(string filePath) { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } return true; }
2.文件上传下载接口和图片大同小异。
using QX_Frame.App.WebApi; using QX_Frame.FilesCenter.Helper; using QX_Frame.Helper_DG; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Http; /** * author:qixiao * create:2017-5-26 16:54:46 * */ namespace QX_Frame.FilesCenter.Controllers { public class FilesController : WebApiControllerBase { //Get : api/Files public HttpResponseMessage Get(string fileName) { HttpResponseMessage result = null; DirectoryInfo directoryInfo = new DirectoryInfo(IO_Helper_DG.RootPath_MVC + @"Files/Files"); FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault(); if (foundFileInfo != null) { FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(fs); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name; } else { result = new HttpResponseMessage(HttpStatusCode.NotFound); } return result; } //POST : api/Files public async Task<IHttpActionResult> Post() { //get server root physical path string root = IO_Helper_DG.RootPath_MVC; //new folder string newRoot = root + @"Files/Files/"; //check path is exist if not create it IO_Helper_DG.CreateDirectoryIfNotExist(newRoot); List<string> fileNameList = new List<string>(); StringBuilder sb = new StringBuilder(); long fileTotalSize = 0; int fileIndex = 1; //get files from request HttpFileCollection files = HttpContext.Current.Request.Files; await Task.Run(() => { foreach (var f in files.AllKeys) { HttpPostedFile file = files[f]; if (!string.IsNullOrEmpty(file.FileName)) { string fileLocalFullName = newRoot + file.FileName; file.SaveAs(fileLocalFullName); fileNameList.Add($"Files/Files/{file.FileName}"); FileInfo fileInfo = new FileInfo(fileLocalFullName); fileTotalSize += fileInfo.Length; sb.Append($" #{fileIndex} Uploaded file: {file.FileName} ({ fileInfo.Length} bytes)"); fileIndex++; Trace.WriteLine("1 file copied , filePath=" + fileLocalFullName); } } }); return Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($"{fileNameList.Count} file(s) /{fileTotalSize} bytes uploaded successfully! Details -> {sb.ToString()}", fileNameList, fileNameList.Count)); } } }
实现了上述两个控制器代码以后,我们需要前端代码来调试对接,代码如下所示。
<!doctype> <head> <script src="jquery-3.2.0.min.js"></script> <!--<script src="jquery-1.11.1.js"></script>--> <!--<script src="ajaxfileupload.js"></script>--> <script> $(document).ready(function () { var appDomain = "http://localhost:3997/"; $("#btn_fileUpload").click(function () { /** * 用ajax方式上传文件 ----------- * */ //-------asp.net webapi fileUpload // var formData = new FormData($("#uploadForm")[0]); $.ajax({ url: appDomain + 'api/Files', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (data) { console.log(JSON.stringify(data)); }, error: function (data) { console.log(JSON.stringify(data)); } }); //----end asp.net webapi fileUpload //----.net core webapi fileUpload // var fileUpload = $("#files").get(0); // var files = fileUpload.files; // var data = new FormData(); // for (var i = 0; i < files.length; i++) { // data.append(files[i].name, files[i]); // } // $.ajax({ // type: "POST", // url: appDomain+'api/Files', // contentType: false, // processData: false, // data: data, // success: function (data) { // console.log(JSON.stringify(data)); // }, // error: function () { // console.log(JSON.stringify(data)); // } // }); //--------end net core webapi fileUpload /** * ajaxfileupload.js 方式上传文件 * */ // $.ajaxFileUpload({ // type: 'post', // url: appDomain + 'api/Files', // secureuri: false, // fileElementId: 'files', // success: function (data) { // console.log(JSON.stringify(data)); // }, // error: function () { // console.log(JSON.stringify(data)); // } // }); }); //end click }) </script> </head> <title></title> <body> <article> <header> <h2>article-form</h2> </header> <p> <form action="/" method="post" id="uploadForm" enctype="multipart/form-data"> <input type="file" id="files" name="files" placeholder="file" multiple>file-multiple属性可以选择多项<br><br> <input type="button" id="btn_fileUpload" value="fileUpload"> </form> </p> </article> </body>
至此,我们的功能已全部实现,下面我们来测试一下:
可见,文件上传成功,按预期格式返回!
下面我们测试单图片上传->
然后我们按返回的地址进行访问图片地址。
发现并无任何压力!
下面测试多图片上传->
完美~
至此,我们已经实现了WebApi2文件和图片上传,下载的全部功能。
这里需要注意一下Web.config的配置上传文件支持的总大小,我这里配置的是最大支持的文件大小为1MB
<requestFiltering> <requestLimits maxAllowedContentLength="1048576" /> </requestFiltering> <system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <security> <requestFiltering> <requestLimits maxAllowedContentLength="1048576" /><!--1MB--> </requestFiltering> </security> </system.webServer>
【相关推荐】
3. 详细介绍ASP.NET MVC--控制器(controller)
以上是分享WebApi2 文件图片上传与下载功能实例的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

红果短剧不仅是一个观赏短剧的平台,更是一个内容丰富的宝库,其中还包括了小说等精彩内容。对于许多热爱阅读的用户来说,这无疑是一个巨大的惊喜。然而很多用户们还不太了解究竟该如何在红果短剧中下载并观看这些小说内容,在下文中本站小编就将为大家带来详细的下载步骤介绍,希望能帮助到各位有需要的小伙伴们。红果短剧怎样下载观看答案:【红果短剧】-【听书】-【文章】-【下载】。具体步骤:1、首先打开红果短剧软件,进入到首页中后我们点击页面上方的【听书】按钮;2、然后在小说的页面中我们可以看到有很多的文章内容,在这

当你在自己电脑上登过别人steam账号之后,恰巧这个别人的账号也有wallpaper软件,切换回自己账号之后steam就会自动下载别人账号订阅的壁纸,用户可以通过关闭steam云同步解决。wallpaperengine登录别的号后下载别人的壁纸怎么办1、登陆你自己的steam账号,在设置里面找到云同步,关闭steam云同步。2、登陆你之前登陆的别人的steam账号,打开wallpaper创意工坊,找到订阅内容,然后取消全部订阅。(以后防止找不到壁纸,可以先收藏再取消订阅)3、切换回自己的stea

最近有很多用户都在问小编,115://开头的链接怎么下载?想要下载115://开头的链接需要借助115浏览器,大家下载好115浏览器后,再来看看下面小编整理好的下载教程吧。 115://开头的链接下载方法介绍 1、登录115.com,下载115浏览器并安装。 2、在115浏览器地址栏输入:chrome://extensions/,进入扩展中心,搜索Tampermonkey,安装对应插件。 3、在115浏览器地址栏输入: 油猴脚本:https://greasyfork.org/en/

超级人类(superpeople)游戏可以通过steam客户端下载游戏,这款游戏的大小在28G左右,下载到安装通常需要一个半小时,下面为大家带来具体的下载安装教程!新的申请全球封闭测试方法1)在Steam商店(steam客户端下载)搜索“SUPERPEOPLE”2)点击“SUPERPEOPLE”商店页面下方的“请求SUPERPEOPLE封闭测试访问权限”3)点击请求访问权限按钮后,将在Steam库中可确认“SUPERPEOPLECBT”游戏4)在“SUPERPEOPLECBT”中点击安装按钮并下

不少的用户们在使用夸克网盘的时候需要将文件下载下来,可我们想让他保存在本地,那么这要怎么设置?下面就让本站来为用户们来仔细的介绍一下夸克网盘下载文件保存回本地的方法吧。 夸克网盘下载文件保存回本地的方法 1、打开夸克,登录账号进去,点击列表图标。 2、点击图标之后,选择网盘。 3、进去夸克网盘之后,点击我的文件。 4、进去我的文件之后,选择要下载的文件,点击三点图标。 5、勾选要下载的文件,点击下载就行了。

foobar2000是一款能随时收听音乐资源的软件,各种音乐无损音质带给你,增强版本的音乐播放器,让你得到更全更舒适的音乐体验,它的设计理念是将电脑端的高级音频播放器移植到手机上,提供更加便捷高效的音乐播放体验,界面设计简洁明了易于使用它采用了极简的设计风格,没有过多的装饰和繁琐的操作能够快速上手,同时还支持多种皮肤和主题,根据自己的喜好进行个性化设置,打造专属的音乐播放器支持多种音频格式的播放,它还支持音频增益功能根据自己的听力情况调整音量大小,避免过大的音量对听力造成损害。接下来就让小编为大

夸克作为一款方便实用的网盘工具,能够帮助用户轻松获取喜欢的资源,如果想将某个文件下载到本地要如何操作呢?下面就由小编来告诉大家,赶快一起学习一下吧!夸克网盘下载到本地方法分享1、首先打开夸克软件,进入到首页之后我们点击右下方的【云图标】;2、然后在夸克网盘的页面中我们点击其中的【文档】功能;3、接着来到文档的页面中选择好需要下载的文件之后点击【三点图标】;4、最后点击过后在弹出的对话框中我们点击【下载】即可;

贝乐虎儿歌作为孩子们成长过程中不可或缺的陪伴,以其欢快的旋律、生动的画面和寓教于乐的内容,赢得了无数家长和孩子们的喜爱。为了让宝贝们能够随时随地享受到儿歌带来的快乐,许多家长都希望能够将贝乐虎儿歌下载到手机或平板上方便随时拿来给孩子听,但是究竟该如何将贝乐虎的儿歌保存到自己的手机上呢,这篇教程就将为大家带来详细的内容介绍,还不了解的用户们就快来跟着本文一起阅读了解一下吧。贝乐虎儿歌下载儿歌多图教程:打开软件,选择一首想要下载的儿歌,小编这里以“经典儿歌”为例2.在儿歌明星的下方点击“下载”按钮,
