. Net Core picture File upload Download

Source: Internet
Author: User
Tags hosting

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:

 1 Using Microsoft.AspNetCore.Builder; 2 Using Microsoft.AspNetCore.Hosting; 3 Using Microsoft.AspNetCore.Http; 4 using Microsoft.Extensions.Configuration; 5 using Microsoft.Extensions.DependencyInjection; 6 using Microsoft.Extensions.FileProviders; 7 Using Microsoft.Extensions.Logging; 8 Using system.io; 9 namespace Qx_core.filescenter11 {public class Startup13 {+ public Startup (ihostingenvironment env ) at {var Builder = new Configurationbuilder () 17. Setbasepath (env. Contentrootpath) 18. Addjsonfile ("appsettings.json", optional:false, Reloadonchange:true) 19. Addjsonfile ($ "appsettings.{ Env. Environmentname}.json ", Optional:true) 20. Addenvironmentvariables (); Configuration = builder. Build ();}23 public Iconfigurationroot Configuration {get;} //this method gets called by the Runtime. Use this method to add services to the Container.27 public void Configureservices (iservicecollection services), {//ADD Framework Service s.30 Services. Addmvc (); #region CORS32 services. Addcors (options =>33 {options. Addpolicy ("allowspecificorigin", builder = builder. Withorigins ("http://localhost:3997"). Allowanyheader (). Allowanyorigin (). Allowanymethod ()); PNs #endregion38}39//this method gets called by the R Untime. Use this method to configure the HTTP request pipeline.41 public void Configure (iapplicationbuilder app, ihostinge Nvironment env, iloggerfactory Loggerfactory) {//loggerfactory.addconsole (configuration.getsectio N ("Logging")),//loggerfactory.adddebug (), and the app. Usemvc ();//shows usecors with named Policy.48 App. Usecors ("allowspecificorigin");Pp. Usestaticfiles (new staticfileoptions () {fileprovider = new Physicalfileprovider (path.comb             ine (directory.getcurrentdirectory (), @ "wwwroot/files"), requestpath = new PathString ("/src") 54 }); 55}56}57}

The code for the

2, RETURN_HELPER_DG class user to set a unified return value back to the client
RETURN_HELPER_DG class is as follows:

 1 Using system.net; 2/** 3 * Author:qixiao 4 * create:2017-5-19 15:15:05 5 * */6 namespace QX_Core.FilesCenter.QX_Core.Helper 7 {8 Publ IC Abstract class RETURN_HELPER_DG 9 {ten public static object Issuccess_msg_data_httpcode (bool issuccess, stri ng msg, dynamic data, httpstatuscode httpcode = httpstatuscode.ok) one {return new {issuccess = IsSu ccess, msg = msg, Httpcode = httpcode, data = data};13}14 public static object Success_msg_data_dcount_h             Ttpcode (string msg, Dynamic Data = null, int datacount = 0, HttpStatusCode httpcode = Httpstatuscode.ok) 15 {16 return new {issuccess = true, msg = msg, Httpcode = httpcode, data = data, Datacount = datacount};17}1 8 public static object Error_msg_ecode_elevel_httpcode (string Msg, int errorCode = 0, int errorLevel = 0, Httpstat  Uscode Httpcode = Httpstatuscode.internalservererror) * {return new {issuccess = false, msg = msg, HtTpcode = httpcode, ErrorCode = errorCode, ErrorLevel = errorLevel};21}22}23} 

3, Filescontroller is our file Upload controller interface, which defines the receive operation on the uploaded file, and enables Cross-domain configuration on the controller

 1 Using Microsoft.AspNetCore.Cors; 2 Using Microsoft.AspNetCore.Hosting; 3 Using Microsoft.AspNetCore.Mvc; 4 using Microsoft.Net.Http.Headers; 5 using QX_Core.FilesCenter.QX_Core.Helper; 6 using System; 7 Using System.Collections.Generic; 8 Using system.io; 9 using system.linq;10 one namespace QX_Core.FilesCenter.Controllers12 {//[produces ("application/json")]14 [Rout          E ("api/[controller]")]15 [enablecors ("allowspecificorigin")]16 public class Filescontroller:controller17 {18 Private ihostingenvironment hostingenv;19 public filescontroller (ihostingenvironment env) 21 {2 2 this.hostingenv = env;23}24 [httppost]26 public iactionresult Post () 27 { The var files = request.form.files;29 Long size = Files.             Sum (f = f.length),//size > 100MB refuse upload!32 if (size > 104857600) 33 {return Json (return_helper_dG.error_msg_ecode_elevel_httpcode ("files Total size > 100MB, server refused!")); }36 PNS list<string> filepathresultlist = new List<string> (); Ch (var file in files)-{contentdispositionheadervalue.parse var fileName = *. Contentdisposition). Filename.trim (' "'); String filePath = Hostingenv.webrootpath + [email protected]" \files\files\ "; If (!                 Directory.Exists (filePath)) (directory.createdirectory (filePath); 48 }49 FileName = Guid.NewGuid () + "." + filename.split ('. ') [1];51-string filefullname = filePath + filename;53-using (FileStream fs = System.IO . File.create (filefullname)). CopyTo FS (fs); Flush ();}59 Filepathresultlist.add ($ "/src/files/{filename} ");}61 String message = $" {Files. Count} file (s)/{size} bytes uploaded successfully! "; return Json (return_helper_dg. Success_msg_data_dcount_httpcode (message, filepathresultlist, filepathresultlist.count)); 65}66 67}68}

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

 1 Using Microsoft.AspNetCore.Cors; 2 Using Microsoft.AspNetCore.Hosting; 3 Using Microsoft.AspNetCore.Mvc; 4 using Microsoft.Net.Http.Headers; 5 using QX_Core.FilesCenter.QX_Core.Helper; 6 using System; 7 Using System.Collections.Generic; 8 Using system.io; 9 using system.linq;10 one namespace QX_Core.FilesCenter.Controllers12 {//[produces ("application/json")]14 [Rout     E ("api/[controller]")]15 [enablecors ("allowspecificorigin")]16 public class Picturescontroller:controller17 {ihostingenvironment hostingenv;19 string[] pictureformatarray = {"png", "jpg", "jpeg", "bm" P "," gif "," ico "," PNG "," JPG "," JPEG "," BMP "," gif "," ico "};21 picturescontroller (ihostingenvironment en V) this.hostingenv = env;25}26 [httppost]28 public iactionresult Pos T () {var files = request.form.files;31 long size = Files.          Sum (f = f.length); 32 33   Size > 100MB refuse upload!34 if (size > 104857600) + + + return Json ( Return_helper_dg. Error_msg_ecode_elevel_httpcode ("pictures Total size > 100MB, server refused!")); Panax notoginseng}38 list<string> filepathresultlist = new List<string> (); Ch (var file in files): {contentdispositionheadervalue.parse var fileName = Contentdisposition). Filename.trim (' "'); FilePath string = Hostingenv.webrootpath + [email protected]" \files\pictures \ ";                 Directory.Exists (filePath)) (directory.createdirectory) (filePath); 50 }51 string suffix = filename.split ('. ') [1];53!pictureformatarray.contains (suffix)] ( Return_helper_dg. Error_msg_ecode_elevel_httpcode ("the picture FOrmat Not support! You must upload files of suffix like ' png ', ' jpg ', ' jpeg ', ' bmp ', ' gif ', ' ico '). }58-page FileName = Guid.NewGuid () + "." + suffix;60-string Filefullna                 me = FilePath + filename;62 the Using (FileStream fs = System.IO.File.Create (filefullname)) 64 {file. CopyTo (fs);             Flush ();}68 filepathresultlist.add ($ "/src/pictures/{filename}"); 69}70 71 String message = $ "{files. Count} file (s)/{size} bytes uploaded successfully! "; return Json (return_helper_dg. Success_msg_data_dcount_httpcode (message, filepathresultlist, filepathresultlist.count)); 74}75 76}77}

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:

 1 <!doctype> 2 3 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!

. Net Core picture File upload Download

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.