前言
前面我们讲过利用AngularJs上传到WebAPi中进行处理,同时我们在MVC系列中讲过文件上传,本文结合MVC+WebAPi来进行文件的同步或者异步上传,顺便回顾下css和js,MVC作为客户端,而WebAPi利用不依赖于IIS的selfhost模式作为服务端来接收客户端的文件且其过程用Ajax来实现,下面我们一起来看看。
同步上传
多余的话不用讲,我们直接看页面。
<div class="container"> <div> @if (ViewBag.Success != null) { <div class="alert alert-danger" role="alert"> <strong>成功啦 !</strong> 成功上传. <a href="@ViewBag.Success" target="_blank">open file</a> </div> } else if (ViewBag.Failed != null) { <div class="alert alert-danger" role="alert"> <strong>失败啦 !</strong> @ViewBag.Failed </div> } </div> @using (Html.BeginForm("SyncUpload", "Home", FormMethod.Post, new { role = "form", enctype = "multipart/form-data", @style = "margin-top:50px;" })) { <div class="form-group"> <input type="file" id="file" name="file" /> </div> <input type="submit" value="Submit" class="btn btn-primary" /> } </div>
上述我们直接上传后通过上传的状态来显示查看上传文件路径并访问,就是这么简单。下面我们来MVC后台逻辑
[HttpPost] public ActionResult SyncUpload(HttpPostedFileBase file) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { byte[] Bytes = new byte[file.InputStream.Length + 1]; file.InputStream.Read(Bytes, 0, Bytes.Length); var fileContent = new ByteArrayContent(Bytes); //设置请求头中的附件为文件名称,以便在WebAPi中进行获取 fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName }; content.Add(fileContent); var requestUri = "http://localhost:8084/api/upload/post"; var result = client.PostAsync(requestUri, content).Result; if (result.StatusCode == System.Net.HttpStatusCode.Created) { //获取到上传文件地址,并渲染到视图中进行访问 var m = result.Content.ReadAsStringAsync().Result; var list = JsonConvert.DeserializeObject<List<string>>(m); ViewBag.Success = list.FirstOrDefault(); } else { ViewBag.Failed = "上传失败啦,状态码:" + result.StatusCode + ",原因:" + result.ReasonPhrase + ",错误信息:" + result.Content.ToString(); } } } return View(); }
注意:上述将获取到文件字节流数组需要传递给 MultipartFormDataContent ,要不然传递到WebAPi时会获取不到文件数据。
到这里为止在MVC中操作就已经完毕,此时我们来看看在WebAPi中需要完成哪些操作。
(1)首先肯定需要判断上传的数据是否是MimeType类型。
if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); }
(2)我们肯定是需要重新生成一个文件名称以免重复,利用Guid或者Date或者其他。
string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name);
(3)我们需要利用此类 MultipartFileStreamProvider 设置上传路径并将文件写入到这个里面。
var provider = new MultipartFileStreamProvider(rootPath); var task = Request.Content.ReadAsMultipartAsync(provider).....
(4) 返回上传文件地址。
return Request.CreateResponse(HttpStatusCode.Created, JsonConvert.SerializeObject(savedFilePath));
分步骤解析了这么多,组装代码如下:
public Task<HttpResponseMessage> Post() { List<string> savedFilePath = new List<string>(); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var substringBin = AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin"); var path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, substringBin); string rootPath = path + "upload"; var provider = new MultipartFileStreamProvider(rootPath); var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData item in provider.FileData) { try { string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name); File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName)); //Request.RequestUri.PathAndQury为需要去掉域名的后面地址 //如上述请求为http://localhost:80824/api/upload/post,这就为api/upload/post //Request.RequestUri.AbsoluteUri则为http://localhost:8084/api/upload/post Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); string fileRelativePath = rootPath +"\\"+ newFileName; Uri fileFullPath = new Uri(baseuri, fileRelativePath); savedFilePath.Add(fileFullPath.ToString()); } catch (Exception ex) { string message = ex.Message; } } return Request.CreateResponse(HttpStatusCode.Created, JsonConvert.SerializeObject(savedFilePath)); }); return task; }
注意:上述item.LocalFileName为 E:\Documents\Visual Studio 2013\Projects\WebAPiReturnHtml\WebAPiReturnHtml\upload\BodyPart_fa01ff79-4a5b-40f6-887f-ab514ec6636f ,因为此时我们重新命名了文件名称,所以需要将该文件移动到我们重新命名的文件地址。
整个过程就是这么简单,下面我们来看看演示结果。
此时居然出错了,有点耐人寻味,在服务端是返回如下的Json字符串
List<string> savedFilePath = new List<string>();
此时进行反序列化时居然出错,再来看看页面上的错误信息:
无法将字符串转换为List
【当将点击查看】时结果如下:
由上知点击查看按钮时返回的才是正确的json,到了这里我们发现Json.NET序列化时也是有问题的,于是乎在进行反序列化时将返回的字符串需要进行一下处理转换成正确的json字符串来再来进行反序列化,修改如下:
var m = result.Content.ReadAsStringAsync().Result; m = m.TrimStart('\"'); m = m.TrimEnd('\"'); m = m.Replace("\\", ""); var list = JsonConvert.DeserializeObject<List<string>>(m);
到这里我们的同步上传告一段落了,这里面利用Json.NET进行反序列化时居然出错问题,第一次遇到Json.NET反序列化时的问题,比较奇葩,费解。
异步上传
所谓的异步上传不过是利用Ajax进行上传,这里也就是为了复习下脚本或者Razor视图,下面的内容只是将视图进行了修改而已,对于异步上传我利用了jquery.form.js中的异步api,请看如下代码:
<script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.form.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <div class="container" style="margin-top:30px"> <div id="success" style="display:none;"> <div class="alert alert-danger" role="alert"> <strong>上传成功</strong><span style="margin-right:50px;"></span><a href="" target="_blank" id="linkAddr">文件访问地址</a> </div> </div> <div id="fail" style="display:none;"> <div class="alert alert-danger" role="alert"> <strong>上传失败</strong> </div> </div> </div> @using (Ajax.BeginForm("AsyncUpload", "Home", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data",@style="margin-top:10px;" })) { <div class="form-group"> <input type="file" name="file" id="fu1" /> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="上传" /> </div> } <div class="form-group"> <div class="progress" id="progress" style="display:none;"> <div class="progress-bar">0%</div> </div> <div id="status"></div> </div> <style> .progress { position: relative; width: 400px; border: 1px solid #ddd; padding: 1px; } .progress-bar { width: 0px; height: 40px; background-color: #57be65; } </style> <script> (function () { var bar = $('.progress-bar'); var percent = $('.progress-bar'); $('form').ajaxForm({ beforeSend: function () { $("#progress").show(); var percentValue = '0%'; bar.width(percentValue); percent.html(percentValue); }, uploadProgress: function (event, position, total, percentComplete) { var percentValue = percentComplete + '%'; bar.width(percentValue); percent.html(percentValue); }, success: function (d) { var percentValue = '100%'; bar.width(percentValue); percent.html(percentValue); $('#fu1').val(''); }, complete: function (xhr) { if (xhr.responseText != null) { $("#linkAddr").prop("href", xhr.responseText); $("#success").show(); } else { $("#fail").show(); } } }); })(); </script>
我们截图看下其中上传过程
上传中:
上传完成:
当然这里的100%不过是针对小文件的实时上传,如果是大文件肯定不是实时的,利用其它组件来实现更加合适,这里我只是学习学习仅此而已。
注意:这里还需重申一遍,之前在MVC上传已经叙述过,MVC默认的上传文件是有限制的,所以超过其限制,则无法上传,需要进行如下设置
(1)在IIS 5和IIS 6中,默认文件上传的最大为4兆,当上传的文件大小超过4兆时,则会得到错误信息,但是我们通过如下来设置文件大小。
<system.web> <httpRuntime maxRequestLength="2147483647" executionTimeout="100000" /> </system.web>
(2)在IIS 7+,默认文件上传的最大为28.6兆,当超过其默认设置大小,同样会得到错误信息,但是我们却可以通过如下来设置文件上传大小(同时也要进行如上设置)。
<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer>
总结
本节我们学习了如何将MVC和WebAPi隔离开来来进行上传,同时我们也发现在反序列化时Json.NET有一定问题,特此记录下,当发现一一对应时反序列化返回的Json字符串不是标准的Json字符串,我们对返回的Json字符串需要作出如下处理才行(也许还有其他方案)。
var jsonString = "返回的json字符串"; jsonString = jsonString.TrimStart('\"'); jsonString = jsonString.TrimEnd('\"'); jsonString = jsonString.Replace("\\", "");
接下来会准备系统学习下SQL Server和Oracle,循序渐进,你说呢!休息,休息!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

C#是一種現代、面向對象的編程語言,由微軟開發並作為.NET框架的一部分。 1.C#支持面向對象編程(OOP),包括封裝、繼承和多態。 2.C#中的異步編程通過async和await關鍵字實現,提高應用的響應性。 3.使用LINQ可以簡潔地處理數據集合。 4.常見錯誤包括空引用異常和索引超出範圍異常,調試技巧包括使用調試器和異常處理。 5.性能優化包括使用StringBuilder和避免不必要的裝箱和拆箱。

C#.NET應用的測試策略包括單元測試、集成測試和端到端測試。 1.單元測試確保代碼的最小單元獨立工作,使用MSTest、NUnit或xUnit框架。 2.集成測試驗證多個單元組合的功能,常用模擬數據和外部服務。 3.端到端測試模擬用戶完整操作流程,通常使用Selenium進行自動化測試。

C#高級開發者面試需要掌握異步編程、LINQ、.NET框架內部工作原理等核心知識。 1.異步編程通過async和await簡化操作,提升應用響應性。 2.LINQ以SQL風格操作數據,需注意性能。 3..NET框架的CLR管理內存,垃圾回收需謹慎使用。

C#.NET面試問題和答案包括基礎知識、核心概念和高級用法。 1)基礎知識:C#是微軟開發的面向對象語言,主要用於.NET框架。 2)核心概念:委託和事件允許動態綁定方法,LINQ提供強大查詢功能。 3)高級用法:異步編程提高響應性,表達式樹用於動態代碼構建。

C#.NET是構建微服務的熱門選擇,因為其生態系統強大且支持豐富。 1)使用ASP.NETCore創建RESTfulAPI,處理訂單創建和查詢。 2)利用gRPC實現微服務間的高效通信,定義和實現訂單服務。 3)通過Docker容器化微服務,簡化部署和管理。

C#和.NET的安全最佳實踐包括輸入驗證、輸出編碼、異常處理、以及身份驗證和授權。 1)使用正則表達式或內置方法驗證輸入,防止惡意數據進入系統。 2)輸出編碼防止XSS攻擊,使用HttpUtility.HtmlEncode方法。 3)異常處理避免信息洩露,記錄錯誤但不返回詳細信息給用戶。 4)使用ASP.NETIdentity和Claims-based授權保護應用免受未授權訪問。

C 語言中冒號 (':') 的含義:條件語句:分隔條件表達式和語句塊循環語句:分隔初始化、條件和增量表達式宏定義:分隔宏名和宏值單行註釋:表示從冒號到行尾的內容為註釋數組維數:指定數組的維數


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver CS6
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。