. Net Core allows you to upload and download image files. netcore

Source: Internet
Author: User

. Net Core allows you to upload and download image files. netcore

Now. the Net Core project has sprung up. net, a member of the army, I warmly embraced. net Core and actively use it for business development. Let's first introduce it.. Net Core project.

I. Development Environment

Undoubtedly, Universe's first IDE Visual Studio 2017

Ii. Project Structure

FilesController file upload and download Controller

PictureController Image Upload/download Controller

Return_Helper_DG returned value help class

Iii. key code

1. First, let's look at Startup. cs, which is our program Startup configuration class. Here we perform a series of configurations.

Cross-origin Configuration:

Of course, dll reference is indispensable for cross-origin. We use Nuget to reference the relevant reference package.

Server resource path replacement, which can prevent the client from guessing the Server File Path and create a virtual stealth for access, thus improving the 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 users set a unified return value to the client.
The code of the Return_Helper_DG class 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 receiving operation for uploaded files and enables cross-origin 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 provide feedback on the file size.

4. The PictureController Image Upload Controller Interface is similar to a file. However, the checksum and restriction of the uploaded image types are imposed.

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)); } }}

At this point, all the file Image Upload code has been completed. Next we will implement the File Upload client.

Iv. Client implementation 

On the client side, we use jQuery Ajax to submit image files. Implementation of client code:

<! Doctype> 

V. Code Testing

1. Start the server

We can see that a console and a web is automatically started, and the web displays the request return value of the default Values controller.

2. upload images

We use ajax to upload images, open the test web page, select images, and Click Upload to view the results returned by the console:

You can see that an image is uploaded successfully!

Enter the returned address. We can see that the image is successfully accessed. Pay special attention to the changes in the server path:

Multi-Image Upload:

It can be seen that there is no problem with uploading multiple images!

Perform the same file upload test:

Likewise, there is no problem with file upload!

Vi. Summary

So far, we have implemented all the expected. Net Core image file upload functions!

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.