從零講解.Net Core開發實現圖片檔上傳下載

巴扎黑
發布: 2018-05-17 11:13:12
原創
8313 人瀏覽過

這篇文章主要為大家詳細介紹了.Net Core實現圖片檔案上傳下載功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

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

 }
}
登入後複製

在上述的程式碼中,我們對上傳的檔案的大小進行了限制,並且對檔案的大小進行回饋。

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

 }
}
登入後複製

到此,我們的文件圖片上傳程式碼已經全部完成,下面我們將文件上傳的客戶端進行實作

四、客戶端的實作

 客戶端我們很簡單地用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+&#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>
登入後複製

五、程式碼測試

#1.啟動伺服器

##我們可以看到一個控制台和一個web自動啟動,並且web顯示預設的Values控制器的請求回傳值。

2.圖片上傳

我們使用ajax的方式進行圖片的上傳操作,打開測試web頁面,並且選擇圖片,點擊上傳,查看控制台返回的結果:

可以看到,一張圖片上傳成功!

輸入回傳的位址,我們可以看到成功存取到了圖片,特別注意這裡伺服器路徑的改變:

多重圖片上傳:

可見,多圖片上傳沒有任何問題!

同樣進行檔案上傳的測試:

#同樣,檔案上傳也沒有任何問題!

六、總結

至此,我們已經實現了預期的.Net Core圖片檔案上傳的全部功能!

以上是從零講解.Net Core開發實現圖片檔上傳下載的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板