Home  >  Article  >  Backend Development  >  Explain .Net Core development to implement image file upload and download from scratch

Explain .Net Core development to implement image file upload and download from scratch

巴扎黑
巴扎黑Original
2018-05-17 11:13:128271browse

This article mainly introduces the .Net Core to implement the image file upload and download function in detail. It has a certain reference value. Interested friends can refer to it

The current .Net Core project is as follows It has sprung up like mushrooms after a rain. As a member of the .Net army, I enthusiastically embraced .Net Core and actively used it for business development. Let's first introduce the file upload and download interface implemented under the .Net Core project.

1. Development environment

Undoubtedly, VisualStudio 2017 is the first IDE in the universe

2 , Project structure

FilesController File upload and download controller

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 perform a series 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 The user sets a unified return value and feeds it back to the client
Return_Helper_DG class The code 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 of uploaded files and enables 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(&#39;"&#39;);

  string filePath = hostingEnv.WebRootPath + $@"\Files\Files\";

  if (!Directory.Exists(filePath))
  {
   Directory.CreateDirectory(filePath);
  }

  fileName = Guid.NewGuid() + "." + fileName.Split(&#39;.&#39;)[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. PictureController picture upload controller interface, similar to files, but with verification and restrictions on the uploaded picture types

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(&#39;"&#39;);

  string filePath = hostingEnv.WebRootPath + $@"\Files\Pictures\";

  if (!Directory.Exists(filePath))
  {
   Directory.CreateDirectory(filePath);
  }

  string suffix = fileName.Split(&#39;.&#39;)[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 &#39;png&#39;,&#39;jpg&#39;,&#39;jpeg&#39;,&#39;bmp&#39;,&#39;gif&#39;,&#39;ico&#39;."));
  }

  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, our file and picture upload code has been completed , below we implement the client side for file upload

IV. Client implementation

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

<!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+&#39;api/Pictures&#39;,
   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

us You 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 Explain .Net Core development to implement image file upload and download from scratch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn