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

一、开发环境

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

.Net Core实现图片文件上传下载功能

二、项目结构

.Net Core实现图片文件上传下载功能

FilesController 文件上传下载控制器

PictureController 图片上传下载控制器

Return_Helper_DG 返回值帮助类

三、关键代码

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

跨域配置:

.Net Core实现图片文件上传下载功能

.Net Core实现图片文件上传下载功能

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

.Net Core实现图片文件上传下载功能

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

.Net Core实现图片文件上传下载功能

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 };
 }
 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是我们的文件上传控制器接口,这里定义了对上传的文件的接收操作,并且在控制器上启用跨域配置

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

  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 !
  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 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="/UploadFiles/2021-04-02/jquery-3.2.0.min.js">

五、代码测试

1.启动服务器

.Net Core实现图片文件上传下载功能

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

2.图片上传

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

.Net Core实现图片文件上传下载功能

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

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

.Net Core实现图片文件上传下载功能

多图片上传:

.Net Core实现图片文件上传下载功能

.Net Core实现图片文件上传下载功能

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

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

.Net Core实现图片文件上传下载功能

.Net Core实现图片文件上传下载功能

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

六、总结

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。