using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Net.Http.Headers; using QX_Core.FilesCenter.QX_Core.Helper; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace QX_Core.FilesCenter.Controllers { //[Produces("application/json")] [Route("api/[controller]")] [EnableCors("AllowSpecificOrigin")] public class PicturesController : Controller { private IHostingEnvironment hostingEnv; string[] pictureFormatArray = { "png", "jpg", "jpeg", "bmp", "gif","ico", "PNG", "JPG", "JPEG", "BMP", "GIF","ICO" }; public PicturesController(IHostingEnvironment env) { this.hostingEnv = env; } [HttpPost] public IActionResult Post() { var files = Request.Form.Files; long size = files.Sum(f => f.Length); //size > 100MB refuse upload ! if (size > 104857600) { return Json(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("pictures total size > 100MB , server refused !")); } List<string> filePathResultList = new List<string>(); foreach (var file in files) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string filePath = hostingEnv.WebRootPath + $@"\Files\Pictures\"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string suffix = fileName.Split('.')[1]; if (!pictureFormatArray.Contains(suffix)) { return Json(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("the picture format not support ! you must upload files that suffix like 'png','jpg','jpeg','bmp','gif','ico'.")); } fileName = Guid.NewGuid() + "." + suffix; string fileFullName = filePath + fileName; using (FileStream fs = System.IO.File.Create(fileFullName)) { file.CopyTo(fs); fs.Flush(); } filePathResultList.Add($"/src/Pictures/{fileName}"); } string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!"; return Json(Return_Helper_DG.Success_Msg_Data_DCount_HttpCode(message, filePathResultList, filePathResultList.Count)); } } }
到此,我们的文件图片上传代码已经全部完成,下面我们对文件上传的客户端进行实现
四、客户端的实现
客户端我们很简单地用jQuery Ajax的方式进行图片文件的提交,客户端代码的实现:
<!doctype> <head> <script src="https://www.jb51.net/jquery-3.2.0.min.js"></script> <script> $(document).ready(function () { var appDomain = "http://localhost:53972/"; $("#btn_fileUpload").click(function () { 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/Pictures', contentType: false, processData: false, data: data, 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 enctype="multipart/form-data"> <input type="file" placeholder="file" multiple>file-multiple属性可以选择多项<br><br> <input type="button" value="fileUpload"> </form> </p> </article> </body>
五、代码测试
1.启动服务器
我们可以看到一个控制台和一个web自动启动,并且web显示默认的Values控制器的请求返回值。
2.图片上传
我们使用ajax的方式进行图片的上传操作,打开测试web页面,并且选择图片,点击上传,查看控制台返回的结果:
可以看到,一张图片上传成功!
输入返回的地址,我们可以看到成功访问到了图片,特别注意这里服务器路径的改变:
多图片上传:
可见,多图片上传没有任何问题!
同样进行文件上传的测试:
同样,文件上传也没有任何问题!
六、总结
至此,我们已经实现了预期的.Net Core图片文件上传的全部功能!