Share a tutorial on using. Net Core implementation image upload download

Source: Internet
Author: User
Tags hosting
This article mainly for you to introduce in detail the. Net core implementation of image file upload download function, with a certain reference value, interested in small partners can refer to

The current. Net core project is springing up and growing as a. NET Army, I warmly embraced. NET core and actively used it for business development, we first introduced the next. NET core project to implement the file upload download interface.

First, the development environment

Undoubtedly, the universe first IDE VisualStudio 2017

II. Structure of the project

Filescontroller File Upload Download controller

Picturecontroller image upload Download controller

RETURN_HELPER_DG Return value Helper class

Three, the key code

1, first we look at Startup.cs this is our program launch configuration class, where we do a series of configuration.

Cross-Domain Configuration:

Of course, cross-domain and DLL references, we use NuGet to reference the relevant reference package

Server resource path substitution, which prevents the client from guessing service-side file paths, creating a virtual insinuate for access, and improving security.

The complete code for 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 set a unified return value feedback to the client
The code for 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 h  Ttpcode = 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 receive operation for 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 (' "');  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}"); The 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 feedback the size of the file.

4, Picturecontroller image upload controller interface, similar to the file, but the upload of the type of the picture is checked and limited


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 isn't support!  You must upload files which 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}"); The string message = $ "{files.  Count} file (s)/{size} bytes uploaded successfully! "; Return Json (RETURN_HELPER_DG. Success_msg_data_dcount_httpcode (Message, filepathresultlist, Filepathresultlist.count)); } }}

To this, our file image upload code has been completed, the following we have uploaded to the file client implementation

Iv. Implementation of the client

Client we are very simple to use jquery Ajax method of image file submission, the implementation of the client code:


<!doctype>

Five, code testing

1. Start the server

We can see a console and a Web autostart, and the Web displays the default values for the value controller's request return.

2. Image upload

We use the Ajax way to upload images, open the test Web page, and select the image, click Upload, to see the results of the console return:

Can see, a picture upload success!

Enter the return address, we can see the successful access to the picture, pay special attention to the change of server path here:

Multi-image upload:

Visible, multi-image upload without any problems!

The same test for file upload:

Also, file upload does not have any problems!

Vi. Summary

So far, we've implemented all the features of the expected. Net core image file uploads!

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.