当下.Net Core项目可是如雨后春笋一般发展起来,作为.Net大军中的一员,我热忱地拥抱了.Net Core并且积极使用其进行业务的开发,我们先介绍下.Net Core项目下实现文件上传下载接口。

一、开发环境

毋庸置疑,宇宙第一IDE VisualStudio 2017

二、项目结构

FilesController 文件上传下载控制器

PictureController 图片上传下载控制器

Return_Helper_DG 返回值帮助类

三、关键代码

1、首先我们来看Startup.cs 这个是我们的程序启动配置类,在这里我们进行一系列的配置。

跨域配置:

当然跨域少不了dll的引用,我们使用Nuget引用相关的引用包

服务器资源路径置换,这样可以防止客户端猜测服务端文件路径,制造一个虚拟的隐射进行访问,提高了安全性。

Startup.cs的完整代码如下:

 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类用户设置一个统一的返回值反馈到客户端
Return_Helper_DG类的代码如下:

 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 };
         }
         , HttpStatusCode httpCode = HttpStatusCode.OK)
         {
             return new { isSuccess = true, msg = msg, httpCode = httpCode, data = data, dataCount = dataCount };
         }
         , , HttpStatusCode httpCode = HttpStatusCode.InternalServerError)
         {
             return new { isSuccess = false, msg = msg, httpCode = httpCode, errorCode = errorCode, errorLevel = errorLevel };
         }
     }
 }

3、FilesController是我们的文件上传控制器接口,这里定义了对上传的文件的接收操作,并且在控制器上启用跨域配置

 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 !
             )
             {
                 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() + ];

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

     }
 }

在上述的代码中,我们对上传的文件的大小进行了限制,并且对文件的大小进行反馈。

4、PictureController 图片上传控制器接口,类似于文件,不过对上传的图片类型进行了校验和限制

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

                 ];

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

     }
 }

到此,我们的文件图片上传代码已经全部完成,下面我们对文件上传的客户端进行实现

四、客户端的实现

客户端我们很简单地用jQuery Ajax的方式进行图片文件的提交,客户端代码的实现:

 <!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+'api/Pictures',
                     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>

五、代码测试

1.启动服务器

我们可以看到一个控制台和一个web自动启动,并且web显示默认的Values控制器的请求返回值。

2.图片上传

我们使用ajax的方式进行图片的上传操作,打开测试web页面,并且选择图片,点击上传,查看控制台返回的结果:

可以看到,一张图片上传成功!

输入返回的地址,我们可以看到成功访问到了图片,特别注意这里服务器路径的改变:


多图片上传:

可见,多图片上传没有任何问题!


同样进行文件上传的测试:

同样,文件上传也没有任何问题!

六、总结

至此,我们已经实现了预期的.Net Core图片文件上传的全部功能!

.Net Core 图片文件上传下载的更多相关文章

  1. JAVA Web 之 struts2文件上传下载演示(一)(转)

    JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...

  2. JavaWeb 文件上传下载

    1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端,从服务器端下载文件到本地的过程.例如目前网站需要上传头像.上传下载图片或网盘等功能都是利用文件上传下 ...

  3. SpringMVC(三) RESTful架构和文件上传下载

    RESTful架构 REST全名为:Representational State Transfer.资源表现层状态转化.是目前最流行的一种互联网软件架构. 它结构清晰.符合标准.易于理解.扩展方便,所 ...

  4. 转载:JavaWeb 文件上传下载

    转自:https://www.cnblogs.com/aaron911/p/7797877.html 1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端 ...

  5. Struts的文件上传下载

    Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...

  6. JavaWeb实现文件上传下载功能实例解析

    转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...

  7. JAVA Web 之 struts2文件上传下载演示(二)(转)

    JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...

  8. java web 文件上传下载

    文件上传下载案例: 首先是此案例工程的目录结构:

  9. 文件上传下载样式 --- bootstrap

    在平时工作中,文件上传下载功能属于不可或缺的一部分.bootstrap前端样式框架也使用的比较多,现在根据bootstrap强大的样式模板,自定义一种文件下载的样式. 后续会使用spring MVC框 ...

随机推荐

  1. Angular2.js——主从结构

    学习这一篇的内容,还回到我们快速起步的应用上来. 主从结构,我们想要做一个英雄的列表,我们希望用户在列表中选中一个英雄,然后这个被选中的英雄出现在详情视图中.主视图是英雄列表,从视图则是被选中英雄的详 ...

  2. bzoj4784 [Zjoi2017]仙人掌

    Description 如果一个无自环无重边无向连通图的任意一条边最多属于一个简单环,我们就称之为仙人掌.所谓简单环即不经过重复的结点的环. 现在九条可怜手上有一张无自环无重边的无向连通图,但是她觉得 ...

  3. PHP填补数字前后的0

    PHP数字填补0 经常会遇到这样的问题: 自然数字是0,1,2,3...而我们需要的却是满足多少多少位数的数字,如:001,002. 在ID,编号,学号中我们会经常用到补全前面或者后面的空位(一般为前 ...

  4. AspNetCore-MVC实战系列(四)之结尾

    AspNetCore - MVC实战系列目录 . 爱留图网站诞生 . git源码:https://github.com/shenniubuxing3/LovePicture.Web . AspNetC ...

  5. 在SOUI中支持高分屏显示

    和手机屏幕一样,高分屏在PC上使用越来越多.传统的桌面程序都是像素为单位进行UI布局,而且是适配传统的96dpi的显示器的.这就导致这些程序在高分屏上显示很小,用户用起来很难受. 虽然windows系 ...

  6. String转int数字格式异常问题

     写在前面的话 差不多一年前就计划写博客,可因为种种原因一直没有写,反而我身边的一些同学在我建议他们写博客不久之后就写了,比如张博同学,基本每次总结一个知识点就写一篇,这样不但方便自己以后查看翻阅,也 ...

  7. 构建你人生里的第一个 Laravel 项目

    安装 Laravel 安装器 composer global require "laravel/installer" 创建项目 laravel new links 检查是否安装成功 ...

  8. LINQ基础(一)

    LINQ(Language Integrated Query,语言集成查询),在C#语言中集成了查询语法,可以用相同的语法访问不同的数据源. LINQ提供了不同数据源的抽象层,所以可以使用相同的语法. ...

  9. 最近一些朋友问我,临近快毕业了专业不对口,想转行看到IT行业就业前景不错,但是编程语言众多不了解,不知道哪门语言能够快速入门掌握,短期能让我找到工作

    我做互联网前端后台开发也有四年多了,一路走过来,累并快乐着.快乐比艰辛更多,源自我的兴趣驱动.初中的一个偶然的机会我接触到了计算机,从那个时候就喜欢上开始经常到网吧上网.那个时候我对计算机领域的认识是 ...

  10. jquery之效果操作

    jQuery操作之效果 效果一共分五大类 一.基本 二.滑动 三.淡入淡出 四.自定义 五.设置 咱们先来看一下基本类 一.基本又分为 show() hide() toggle() html代码 &l ...