


Share an example tutorial on uploading and downloading images using .Net Core
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the "My" button in the lower right corner; (2) On the personal center page, find "Settings" and click it; (3) Scroll down and find the "Clear Cache" option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the "Comment" button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a "picture" button or a "+" button, click

Apple's recent iPhones capture memories with crisp detail, saturation and brightness. But sometimes, you may encounter some issues that may cause the image to look less clear. While autofocus on iPhone cameras has come a long way, allowing you to take photos quickly, the camera can mistakenly focus on the wrong subject in certain situations, making the photo blurry in unwanted areas. If your photos on your iPhone look out of focus or lack sharpness overall, the following post should help you make them sharper. How to Make Pictures Clearer on iPhone [6 Methods] You can try using the native Photos app to clean up your photos. If you want more features and options

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

Are you also using Foxit PDF Reader software? So do you know how Foxit PDF Reader converts pdf documents into jpg images? The following article brings you how Foxit PDF Reader converts pdf documents into jpg images. For those who are interested in the method of converting jpg images, please come and take a look below. First start Foxit PDF Reader, then find "Features" on the top toolbar, and then select the "PDF to Others" function. Next, open a web page called "Foxit PDF Online Conversion". Click the "Login" button on the upper right side of the page to log in, and then turn on the "PDF to Image" function. Then click the upload button and add the pdf file you want to convert into an image. After adding it, click "Start Conversion"

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select "Page Layout". 2. Select "Tight wrapping" in text wrapping. 3. After all the pictures you need are confirmed to be set to "Tight text wrapping", you can drag the pictures to the appropriate position and click on the first picture.

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.
