Home Backend Development C#.Net Tutorial Share an example tutorial on uploading and downloading images using .Net Core

Share an example tutorial on uploading and downloading images using .Net Core

Jun 17, 2017 am 10:26 AM
.net core picture accomplish

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")
  });
 }
 }
}
Copy after login

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 };
 }
 }
}
Copy after login

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

 }
}
Copy after login

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

 }
}
Copy after login

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+&#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>
Copy after login

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

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 &quot;My&quot; button in the lower right corner; (2) On the personal center page, find &quot;Settings&quot; and click it; (3) Scroll down and find the &quot;Clear Cache&quot; 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

How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? Mar 21, 2024 pm 09:12 PM

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 &quot;Comment&quot; 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 &quot;picture&quot; button or a &quot;+&quot; button, click

6 Ways to Make Pictures Sharper on iPhone 6 Ways to Make Pictures Sharper on iPhone Mar 04, 2024 pm 06:25 PM

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

How to make ppt pictures appear one by one How to make ppt pictures appear one by one Mar 25, 2024 pm 04:00 PM

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.

How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader How to convert pdf documents into jpg images with Foxit PDF Reader - How to convert pdf documents into jpg images with Foxit PDF Reader Mar 04, 2024 pm 05:49 PM

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? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

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

How to arrange two pictures side by side in wps document How to arrange two pictures side by side in wps document Mar 20, 2024 pm 04:00 PM

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 &quot;Page Layout&quot;. 2. Select &quot;Tight wrapping&quot; in text wrapping. 3. After all the pictures you need are confirmed to be set to &quot;Tight text wrapping&quot;, you can drag the pictures to the appropriate position and click on the first picture.

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

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.

See all articles