我用的是VS2019 Core3.1 。打開Vs2019 建立Asp.Net Core Web應用程序命名CoreWebApi 建立選擇API 在Controller文件夾下面添加一個Api控制器 FileUp,修改Api的路由 [Route("api/[controller]/[action]")] 這樣就能夠訪問到具體的某一個了 寫一個測試 apijavascript
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace CoreWebApi.Controllers { [Route("api/[controller]/[action]")]//修改路由 //[Route("api/[controller]")]//默認路由 [ApiController] public class FileUpController : ControllerBase { /// <summary> /// 測試接口 /// </summary> /// <returns></returns> [HttpGet] //[HttpGet,Route("Test")]//默認路由 public string Test() { return "這是測試接口"; } } }
寫Api的時候必定要加上,請求方式 post、get 其餘的暫時我沒用到。默認的路由是被我註釋的,修改一下 讓他的訪問時api / 控制器 / 方法名稱。不改也能夠,測試的接口就用註釋的那個特性。而後運行項目,地址欄輸入https://localhost:44376/api/FileUp/Test 前端
在FileUp裏寫一個上傳文件的接口全部代碼都在下,OutPut是一個輸出的類,Dto裏面是一些參數 應該都有看得懂。裏面就是上傳文件儲存到服務器上 並無數據庫操做,須要的加上去就能夠了。java
注意:有些會加[Consumes("application/json")]//application/json//application/x-www-form-urlencoded 這樣來驗證媒體類型,這裏我弄了很久纔想起來我寫了這個。由於文件上傳怎麼說呢,媒體類型確定不會是Json之類的。我之前的Api就是在基礎Api類里加了這個。給我弄了頭皮發麻纔看到jquery
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using CoreWebApi.Models; using Newtonsoft.Json; using Microsoft.Extensions.Hosting; using System.IO; namespace CoreWebApi.Controllers { [Route("api/[controller]/[action]")]//修改路由 //[Route("api/[controller]")]//默認路由 [ApiController] public class FileUpController : ControllerBase { public IHostingEnvironment env; public FileUpController(IHostingEnvironment _env) { env = _env; } /// <summary> /// 測試接口 /// </summary> /// <returns></returns> [HttpGet] //[HttpGet,Route("Test")]//默認路由 public string Test() { return "這是測試接口"; } /// <summary> /// 文件上傳 /// </summary> /// <returns></returns> [HttpPost] public async Task<OutPut> FileUp() { var ret = new OutPut(); try { //不能用FromBody var dto = JsonConvert.DeserializeObject<ImagesDto>(Request.Form["ImageModelInfo"]);//文件類實體參數 var files = Request.Form.Files;//接收上傳的文件,可能多個 看前臺 if (files.Count > 0) { var path = env.ContentRootPath + @"/Uploads/Images/";//絕對路徑 string dirPath = Path.Combine(path, dto.Type + "/");//絕對徑路 儲存文件路徑的文件夾 if (!Directory.Exists(dirPath))//查看文件夾是否存在 Directory.CreateDirectory(dirPath); var file = files.Where(x => true).FirstOrDefault();//只取多文件的一個 var fileNam = $"{Guid.NewGuid():N}_{file.FileName}";//新文件名 string snPath = $"{dirPath + fileNam}";//儲存文件路徑 using var stream = new FileStream(snPath, FileMode.Create); await file.CopyToAsync(stream); //次出還能夠進行數據庫操做 保存到數據庫 ret = new OutPut { Code = 200, Msg = "上傳成功", Success = true }; } else//沒有圖片 { ret = new OutPut { Code = 400, Msg = "請上傳圖片", Success = false }; } } catch (Exception ex) { ret = new OutPut { Code = 500, Msg = $"異常:{ex.Message}", Success = false }; } return ret; } } }
Dto與返回的類ajax
/// <summary> /// 返回輸出類 /// </summary> public class OutPut { /// <summary> /// 狀態碼 /// </summary> public int Code { get; set; } /// <summary> /// 消息 /// </summary> public string Msg { get; set; } /// <summary> /// 是否成功 /// </summary> public bool Success { get; set; } /// <summary> /// 返回數據 /// </summary> public object Data { get; set; } } /// <summary> /// 接收參數Dto /// </summary> public class ImagesDto { /// <summary> /// ID /// </summary> public int ID { get; set; } /// <summary> /// 名稱 /// </summary> public string Name { get; set; } /// <summary> /// 地址 /// </summary> public string Url { get; set; } /// <summary> /// 備註 /// </summary> public string Remark { get; set; } /// <summary> /// /// </summary> public int RelationId { get; set; } /// <summary> /// 類型 /// </summary> public int Type { get; set; } }
我在一個MVC程序裏面用了個Ajax調用 下面是前端代碼,contentType這個資源的類型我轉載着坑裏很久了,哈哈。數據庫
@{ ViewBag.Title = "測試"; } <h2>文件上傳測試</h2> <form enctype="multipart/form-data" id="formData"> <div> <br /><br /><br /> 文件:<input type="file" id="filesp" name="filesp" /><br /><br /> 名稱:<input type="text" id="fileName" name="fileName" /><br /><br /> 備註:<input type="text" id="txtRemake" name="txtRemake" /><br /><br /> RelationId:<input type="number" id="txtRelationId" name="txtRelationId" /><br /><br /> 類型:<select id="selType" name="selType"> <option value="1">動物</option> <option value="2">植物</option> <option value="3">妹子</option> <option value="3">風景</option> <option value="4">滑稽</option> <option value="100">其餘</option> </select> <br /><br /> <input type="button" id="btnSave" name="btnSave" value="提交" /> </div> </form> <script src="~/Scripts/jquery-3.3.1.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnSave").click(function () { var data = new FormData(document.getElementById("formData")); //參數 var parame = JSON.stringify({ Name: $("#fileName").val(), Remark: $("#txtRemake").val(), Type: $("#selType").val(), RelationId: $("#txtRelationId").val() }); data.append("ImageModelInfo", parame); $.ajax({ type: "post", url: "https://localhost:44376/api/FileUp/FileUp", dataType: "json", data: data, async: true, contentType: false,//實體頭部用於指示資源的MIME類型 media type 。這裏要爲false processData: false,//processData 默認爲true,當設置爲true的時候,jquery ajax 提交的時候不會序列化 data,而是直接使用data success: function (data) { console.log(data); }, error: function (data) { console.log("錯誤" + data); } }); }); }); </script>
運行起來看看 測試一下 ,Api那邊也打好斷點。打來瀏覽器調式就是很熟悉的bug就來了(一天看不到出錯彷彿內心不踏實)json
很明顯的CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。它容許瀏覽器向跨源服務器,發出XMLHttpRequest
請求,從而克服了AJAX只能同源使用的限制。因此這裏咱們就要容許前端來訪問,從而就要在Api增長跨域;api
在Startup.cs下面的ConfigureServices 中標添加services.AddCors(option => option.AddPolicy("AllowCors", bu => bu.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));跨域
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //跨域 services.AddCors(option => option.AddPolicy("AllowCors", bu => bu.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); }
AllowAnyOrigin :容許CORS請求從任何源來訪問,這是不安全的
AllowAnyHeader:容許全部的請求頭瀏覽器
AllowCredentials :服務端也須要容許證書。
AllowAnyMethod容許跨域策略容許全部的方法:GET/POST/PUT/DELETE 等方法 若是進行限制須要 AllowAnyMethod("GET","POST") 這樣來進行訪問方法的限制
在Configure中添加中間件app.UseCors("AllowCors");,集體要限制哪些看我的了
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); //跨域 app.UseCors("AllowCors"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
如今就配置好了在須要跨域的地方加上特性[EnableCors("AllowCors")]就好了 ,引用命名空間using Microsoft.AspNetCore.Cors;
[EnableCors("AllowCors")] [Route("api/[controller]/[action]")]//修改路由 //[Route("api/[controller]")]//默認路由 [ApiController] public class FileUpController : ControllerBase { public IHostingEnvironment env; public FileUpController(IHostingEnvironment _env) { env = _env; } /// <summary> /// 測試接口 /// </summary> /// <returns></returns> [HttpGet] //[HttpGet,Route("Test")]//默認路由 public string Test() { return "這是測試接口"; }
如今再來調用就解決了
前臺結果看看。文件夾也建立了。
若是全部Api都要跨域的話就創建一個基礎的Api 讓全部的都繼承這個Api,就須要打賞跨域的標籤就能夠了;
文件上傳還能夠用From直接提交這邊用List<IFormFile>接收,也能夠像FromBady同樣的一個來接收搞,單詞 忘了0.0,參數不能FermBody接收,這樣文件就沒了。
紙上得來終覺淺,覺知這事不寫仍是不行哈。