.net core2.2上传文件总结
总结一下.net core的上传文件操作,这里主要分上传到本地的也就是MVC的,另一种是上传到WebAPi的.
一、Web端
1.新建一个.net core mvc项目
2.这里的版本是.net core 2.2.4
3.新建一个控制器 TestController
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; namespace Web.Controllers { public class TestController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public TestController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public IActionResult Index() { return View(); } /// <summary> /// 上传图片 /// </summary> /// <returns></returns> [HttpPost] public string UploadFiles(string z) { long size = 0; var path = ""; var files = Request.Form.Files; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); string fileExt = Path.GetExtension(file.FileName); //文件扩展名 long fileSize = file.Length; //获得文件大小,以字节为单位 string newFileName = System.Guid.NewGuid().ToString() + fileExt; //随机生成新的文件名 path = "/upload/" + newFileName; path = _hostingEnvironment.WebRootPath + $@"\{path}"; size += file.Length; using (FileStream fs = System.IO.File.Create(path)) { file.CopyTo(fs); fs.Flush(); } path = "/upload/" + newFileName; } return path; } } }
4.新建页面Index
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <form id="form0"> <input type="file" name="file" /> <input type="button" value="上传本地" onclick="upload()" /> </form> </body> </html> <script src="~/lib/jquery/dist/jquery.js"></script> <script src="~/js/jquery.form.js"></script> <script> function upload() { var formData = new FormData($("#form0")[0]); $.ajax({ url: "/test/UploadFiles", data: formData, contentType: false, processData: false, cache: false, type: 'post', success: function (d) { console.log(d); } }) } </script>
5.注意:默认所有的静态文件都放在wwwroot 所以这里我在wwwroot下创建了文件夹upload从来存储文件
这样Web端的上传文件就搞定了
二、WebApi端
1.新建一个webapi项目
2.新建一个api控制器 TestApiController
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace WebApi.Controllers { [EnableCors("AllowSameDomain")]//跨域 [Route("api/[controller]/[action]")] [ApiController] public class TestApiController : ControllerBase { private readonly IHostingEnvironment _hostingEnvironment; public TestApiController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } [HttpPost] public ResultObject UploadIForm(List<IFormFile> files) { List<String> filenames = new List<string>(); foreach (var file in files) { var fileName = file.FileName; Console.WriteLine(fileName); fileName = $"/UploadFile/{fileName}"; filenames.Add(fileName); fileName = _hostingEnvironment.WebRootPath + fileName; using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } return new ResultObject { state = "Success", resultObject = filenames }; } [HttpPost] public string Upload(IFormCollection Files) { try { //var form = Request.Form;//直接从表单里面获取文件名不需要参数 string dd = Files["File"]; var form = Files;//定义接收类型的参数 Hashtable hash = new Hashtable(); IFormFileCollection cols = Request.Form.Files; if (cols == null || cols.Count == 0) { return JsonConvert.SerializeObject(new { status = -1, message = "没有上传文件", data = hash }); } foreach (IFormFile file in cols) { //定义图片数组后缀格式 string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" }; //获取图片后缀是否存在数组中 string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper(); if (LimitPictureType.Contains(currentPictureExtension)) { //为了查看图片就不在重新生成文件名称了 // var new_path = DateTime.Now.ToString("yyyyMMdd")+ file.FileName; var new_path = Path.Combine("uploads/images/", file.FileName); var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", new_path); using (var stream = new FileStream(path, FileMode.Create)) { //图片路径保存到数据库里面去 bool flage = true; if (flage == true) { //再把文件保存的文件夹中 file.CopyTo(stream); hash.Add("file", "/" + new_path); } } } else { return JsonConvert.SerializeObject(new { status = -2, message = "请上传指定格式的图片", data = hash }); } } return JsonConvert.SerializeObject(new { status = 0, message = "上传成功", data = hash }); } catch (Exception ex) { return JsonConvert.SerializeObject(new { status = -3, message = "上传失败", data = ex.Message }); } } } public class ResultObject { public String state { get; set; } public Object resultObject { get; set; } } }
3.这里前台页面还是通过ajax来请求api的,所以就需要进行跨域
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //允许一个或多个具体来源: services.AddCors(options => { // Policy 名稱 CorsPolicy 是自訂的,可以自己改 //跨域规则的名称 options.AddPolicy("AllowSameDomain", policy => { // 設定允許跨域的來源,有多個的話可以用 `,` 隔開 policy .WithOrigins("http://127.0.0.1:53189", "http://localhost:53189") //.AllowAnyOrigin()//允许所有来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("AllowSameDomain");//必须位于UserMvc之前 app.UseMvc(); } } }
4.前台页面 还是用这个方法,url改下
function upload1() { var formData = new FormData($("#form0")[0]); $.ajax({ url: "http://127.0.0.1:8067/api/testapi/Upload", data: formData, contentType: false, processData: false, cache: false, type: 'post', success: function (d) { console.log(d); } }) }
5.将webapi发布到iis
6.同样的,静态文件还是在wwwroot下,api发布后是没有wwwroot文件夹的,所以直接建 /wwwroot/upload文件夹
这样上传就搞定了
莫谈他人高薪,且看闲时谁在拼.