This article mainly introduces the .Net Core implementation of the picture file upload download function in detail, which has a certain reference value. Interested friends can refer to it
Now The .Net Core project has sprung up like mushrooms after a rain. As a member of the .Net army, I have enthusiastically embraced .Net Core and actively used it for business development. Let’s first introduce the implementation of file upload and download under the .Net Core project. interface.
1. Development environment
Undoubtedly, VisualStudio 2017 is the first IDE in the universe
2 , Project structure
FilesController File upload and downloadController
PictureController Picture upload and download controller
Return_Helper_DG Return value help class
3. Key code
1. First, let’s look at Startup.cs. This is our program startup configuration class. Here we proceed A range of configurations.
Cross-domain configuration:
Of course, cross-domain references are indispensable for dlls. We use Nuget to reference related reference packages.
#Server resource path replacement, which can prevent the client from guessing the server file path and create a virtual shadow for access, which improves security.
The complete code of Startup.cs is as follows:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using System.IO; namespace QX_Core.FilesCenter { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); #region CORS services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://localhost:3997").AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod()); }); #endregion } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //loggerFactory.AddConsole(Configuration.GetSection("Logging")); //loggerFactory.AddDebug(); app.UseMvc(); // Shows UseCors with named policy. app.UseCors("AllowSpecificOrigin"); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Files")), RequestPath = new PathString("/src") }); } } }
2. Return_Helper_DG class user sets a unified return value The code of the
Return_Helper_DG class that is fed back to the client is as follows:
using System.Net; /** * author:qixiao * create:2017-5-19 15:15:05 * */ namespace QX_Core.FilesCenter.QX_Core.Helper { public abstract class Return_Helper_DG { public static object IsSuccess_Msg_Data_HttpCode(bool isSuccess, string msg, dynamic data, HttpStatusCode httpCode = HttpStatusCode.OK) { return new { isSuccess = isSuccess, msg = msg, httpCode = httpCode, data = data }; } public static object Success_Msg_Data_DCount_HttpCode(string msg, dynamic data = null, int dataCount = 0, HttpStatusCode httpCode = HttpStatusCode.OK) { return new { isSuccess = true, msg = msg, httpCode = httpCode, data = data, dataCount = dataCount }; } public static object Error_Msg_Ecode_Elevel_HttpCode(string msg, int errorCode = 0, int errorLevel = 0, HttpStatusCode httpCode = HttpStatusCode.InternalServerError) { return new { isSuccess = false, msg = msg, httpCode = httpCode, errorCode = errorCode, errorLevel = errorLevel }; } } }
3. FilesController is our file upload controller interface, which defines the reception of uploaded files. Operation, and enable cross-domain configuration on the controller
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 FilesController : Controller { private IHostingEnvironment hostingEnv; public FilesController(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("files 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\Files\"; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } fileName = Guid.NewGuid() + "." + fileName.Split('.')[1]; string fileFullName = filePath + fileName; using (FileStream fs = System.IO.File.Create(fileFullName)) { file.CopyTo(fs); fs.Flush(); } filePathResultList.Add($"/src/Files/{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)); } } }
In the above code, we limit the size of the uploaded file and adjust the size of the file. feedback.
4. PictureController picture upload controller interface, similar to a file, but has checksum restrictions on the type of uploaded pictures
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)); } } }
So far, Our file and image upload code has been completed. Now we will implement the client for file upload
4. Client implementation
We can simply use the client Submit image files using jQuery Ajax, client code implementation:
<!doctype> <head> <script src="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 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>
5. Code test
1. Start the server
#We can see that a console and a web start automatically, and the web displays the request return value of the default Values controller.
2. Image upload
We use ajax to upload images, open the test web page, select the image, click upload, and view the results returned by the console:
You can see that a picture was uploaded successfully!
Enter the returned address, we can see that the image has been successfully accessed, pay special attention to the change of the server path here:
Multiple image uploads:
It can be seen that there is no problem in uploading multiple pictures!
Similarly perform the file upload test:
Similarly, there are no problems with file upload!
6. Summary
So far, we have achieved all the expected .Net Core image file upload functions!
The above is the detailed content of Share an example tutorial on uploading and downloading images using .Net Core. For more information, please follow other related articles on the PHP Chinese website!