1. 程式人生 > >.Net Core 圖片檔案上傳下載

.Net Core 圖片檔案上傳下載

當下.Net Core專案可是如雨後春筍一般發展起來,作為.Net大軍中的一員,我熱忱地擁抱了.Net Core並且積極使用其進行業務的開發,我們先介紹下.Net Core專案下實現檔案上傳下載介面。

一、開發環境

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

二、專案結構

 

FilesController 檔案上傳下載控制器

PictureController 圖片上傳下載控制器

Return_Helper_DG 返回值幫助類

三、關鍵程式碼

1、首先我們來看Startup.cs 這個是我們的程式啟動配置類,在這裡我們進行一系列的配置。

跨域配置:

當然跨域少不了dll的引用,我們使用Nuget引用相關的引用包

 伺服器資源路徑置換,這樣可以防止客戶端猜測服務端檔案路徑,製造一個虛擬的隱射進行訪問,提高了安全性。

Startup.cs的完整程式碼如下:

複製程式碼
 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 10 namespace QX_Core.FilesCenter 11 { 12 public class Startup 13 { 14 public Startup(IHostingEnvironment env) 15 { 16 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(); 21 Configuration = builder.Build(); 22 } 23 24 public IConfigurationRoot Configuration { get; } 25 26 // This method gets called by the runtime. Use this method to add services to the container. 27 public void ConfigureServices(IServiceCollection services) 28 { 29 // Add framework services. 30 services.AddMvc(); 31 #region CORS 32 services.AddCors(options => 33 { 34 options.AddPolicy("AllowSpecificOrigin", 35 builder => builder.WithOrigins("http://localhost:3997").AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod()); 36 }); 37 #endregion 38 } 39 40 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 41 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 42 { 43 //loggerFactory.AddConsole(Configuration.GetSection("Logging")); 44 //loggerFactory.AddDebug(); 45 46 app.UseMvc(); 47 // Shows UseCors with named policy. 48 app.UseCors("AllowSpecificOrigin"); 49 50 app.UseStaticFiles(new StaticFileOptions() 51 { 52 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Files")), 53 RequestPath = new PathString("/src") 54 }); 55 } 56 } 57 }
複製程式碼

2、Return_Helper_DG類使用者設定一個統一的返回值反饋到客戶端
Return_Helper_DG類的程式碼如下:

複製程式碼
 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     public abstract class Return_Helper_DG
 9     {
10         public static object IsSuccess_Msg_Data_HttpCode(bool isSuccess, string msg, dynamic data, HttpStatusCode httpCode = HttpStatusCode.OK)
11         {
12             return new { isSuccess = isSuccess, msg = msg, httpCode = httpCode, data = data };
13         }
14         public static object Success_Msg_Data_DCount_HttpCode(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         }
18         public static object Error_Msg_Ecode_Elevel_HttpCode(string msg, int errorCode = 0, int errorLevel = 0, HttpStatusCode httpCode = HttpStatusCode.InternalServerError)
19         {
20             return new { isSuccess = false, msg = msg, httpCode = httpCode, errorCode = errorCode, errorLevel = errorLevel };
21         }
22     }
23 }
複製程式碼

3、FilesController是我們的檔案上傳控制器介面,這裡定義了對上傳的檔案的接收操作,並且在控制器上啟用跨域配置

複製程式碼
 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 
11 namespace QX_Core.FilesCenter.Controllers
12 {
13     //[Produces("application/json")]
14     [Route("api/[controller]")]
15     [EnableCors("AllowSpecificOrigin")]
16     public class FilesController : Controller
17     {
18         private IHostingEnvironment hostingEnv;
19 
20         public FilesController(IHostingEnvironment env)
21         {
22             this.hostingEnv = env;
23         }
24 
25         [HttpPost]
26         public IActionResult Post()
27         {
28             var files = Request.Form.Files;
29             long size = files.Sum(f => f.Length);
30 
31             //size > 100MB refuse upload !
32             if (size > 104857600)
33             {
34                 return Json(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("files total size > 100MB , server refused !"));
35             }
36 
37             List<string> filePathResultList = new List<string>();
38 
39             foreach (var file in files)
40             {
41                 var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
42 
43                 string filePath = hostingEnv.WebRootPath + $@"\Files\Files\";
44 
45                 if (!Directory.Exists(filePath))
46                 {
47                     Directory.CreateDirectory(filePath);
48                 }
49 
50                 fileName = Guid.NewGuid() + "." + fileName.Split('.')[1];
51 
52                 string fileFullName = filePath + fileName;
53 
54                 using (FileStream fs = System.IO.File.Create(fileFullName))
55                 {
56                     file.CopyTo(fs);
57                     fs.Flush();
58                 }
59                 filePathResultList.Add($"/src/Files/{fileName}");
60             }
61 
62             string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!";
63 
64             return Json(Return_Helper_DG.Success_Msg_Data_DCount_HttpCode(message, filePathResultList, filePathResultList.Count));
65         }
66 
67     }
68 }
複製程式碼

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

4、PictureController 圖片上傳控制器介面,類似於檔案,不過對上傳的圖片型別進行了校驗和限制

複製程式碼
 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 
11 namespace QX_Core.FilesCenter.Controllers
12 {
13     //[Produces("application/json")]
14     [Route("api/[controller]")]
15     [EnableCors("AllowSpecificOrigin")]
16     public class PicturesController : Controller
17     {
18         private IHostingEnvironment hostingEnv;
19 
20         string[] pictureFormatArray = { "png", "jpg", "jpeg", "bmp", "gif","ico", "PNG", "JPG", "JPEG", "BMP", "GIF","ICO" };
21 
22         public PicturesController(IHostingEnvironment env)
23         {
24             this.hostingEnv = env;
25         }
26 
27         [HttpPost]
28         public IActionResult Post()
29         {
30             var files = Request.Form.Files;
31             long size = files.Sum(f => f.Length);
32 
33             //size > 100MB refuse upload !
34             if (size > 104857600)
35             {
36                 return Json(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("pictures total size > 100MB , server refused !"));
37             }
38 
39             List<string> filePathResultList = new List<string>();
40 
41             foreach (var file in files)
42             {
43                 var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
44 
45                 string filePath = hostingEnv.WebRootPath + $@"\Files\Pictures\";
46 
47                 if (!Directory.Exists(filePath))
48                 {
49                     Directory.CreateDirectory(filePath);
50                 }
51 
52                 string suffix = fileName.Split('.')[1];
53 
54                 if (!pictureFormatArray.Contains(suffix))
55                 {
56                     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'."));
57                 }
58 
59                 fileName = Guid.NewGuid() + "." + suffix;
60 
61                 string fileFullName = filePath + fileName;
62 
63                 using (FileStream fs = System.IO.File.Create(fileFullName))
64                 {
65                     file.CopyTo(fs);
66                     fs.Flush();
67                 }
68                 filePathResultList.Add($"/src/Pictures/{fileName}");
69             }
70 
71             string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!";
72 
73             return Json(Return_Helper_DG.Success_Msg_Data_DCount_HttpCode(message, filePathResultList, filePathResultList.Count));
74         }
75 
76     }
77 }
複製程式碼

到此,我們的檔案圖片上傳程式碼已經全部完成,下面我們對檔案上傳的客戶端進行實現

四、客戶端的實現

 客戶端我們很簡單地用jQuery Ajax的方式進行圖片檔案的提交,客戶端程式碼的實現:

複製程式碼
 1 <!doctype>
 2 
 3 <head>
 4     <script src="jquery-3.2.0.min.js"></script>
 5     <script>
 6         $(document).ready(function () {
 7             var appDomain = "http://localhost:53972/";
 8             $("#btn_fileUpload").click(function () {
 9                                 var fileUpload = $("#files").get(0);
10                 var files = fileUpload.files;
11                 var data = new FormData();
12                 for (var i = 0; i < files.length; i++) {
13                       data.append(files[i].name, files[i]);
14                 }
15                 $.ajax({
16                     type: "POST",
17                     url: appDomain+'api/Pictures',
18                     contentType: false,
19                     processData: false,
20                     data: data,
21                     success: function (data) {
22                         console.log(JSON.stringify(data));
23                     },
24                     error: function () {
25                         console.log(JSON.stringify(data));
26                     }
27                 });
28             });
29             //end click
30 
31 
32         })
33     </script>
34 </head>
35 <title></title>
36 
37 <body>
38     <article>
39         <header>
40             <h2>article-form</h2>
41         </header>
42         <p>
43             <form id="uploadForm" enctype="multipart/form-data">
44                 <input type="file" id="files" name="files" placeholder="file" multiple>file-multiple屬性可以選擇多項<br><br>
45                 <input type="button" id="btn_fileUpload" value="fileUpload">
46             </form>
47         </p>
48     </article>
49 </body>
複製程式碼

五、程式碼測試

1.啟動伺服器

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

2.圖片上傳

我們使用ajax的方式進行圖片的上傳操作,開啟測試web頁面,並且選擇圖片,點選上傳,檢視控制檯返回的結果:

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

 輸入返回的地址,我們可以看到成功訪問到了圖片,特別注意這裡伺服器路徑的改變

多圖片上傳:

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

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

 

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

六、總結

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

相關推薦

.Net Core 圖片檔案下載

當下.Net Core專案可是如雨後春筍一般發展起來,作為.Net大軍中的一員,我熱忱地擁抱了.Net Core並且積極使用其進行業務的開發,我們先介紹下.Net Core專案下實現檔案上傳下載介面。 一、開發環境 毋庸置疑,宇宙第一IDE VisualStudio 2

iOS開發之結合asp.net webservice實現檔案下載

iOS開發中會經常用到檔案上傳下載的功能,這篇檔案將介紹一下使用asp.net webservice實現檔案上傳下載。 首先,讓我們看下檔案下載。 這裡我們下載cnblogs上的一個zip檔案。使用NSURLRequest+NSURLConnection可以很方便的實現這個功能。 同步下載檔案:

ASP.NET Core文件下載(多種方式)

long filepath guid sum tool 是我 ajax 控件 host 前段時間項目上線,實在太忙,最近終於開始可以研究研究ASP.NET Core了. 打算寫個系列,但是還沒想好目錄,今天先來一篇,後面在整理吧. ASP.NET Core 2.0

asp.net core 通過ajax圖片及wangEditor圖片

images use class multi jquery 開始 load als org asp.net core 通過ajax上傳圖片 .net core前端代碼,因為是通過ajax調用,首先要保證ajax能調用後臺代碼,具體參見上一篇.net core 使用ajax

ASP.NET Core文件下載與刪除

隨機 sting control 擴展 isa 上傳文件 result load() tip 首先我們需要創建一個form表單如下: <form method="post" enctype="multipart/form-data" asp-controller=

使用.NET SFTP 登陸linux下載檔案

1. 從這裡下載https://github.com/sshnet/SSH.NET 2. 使用wrapper 類 ... public static IList<string> SearchLogs(DateTime fromDate, DateTime toDate) &n

用MVC實現簡單的檔案圖片下載功能

  一 實現效果簡單說明 上傳:上傳圖片,將圖片儲存到伺服器,並將相關資訊寫入資料庫。 下載:在頁面展示圖片下載列表的縮圖,點選圖片將其載入到本地。   二.View Index中程式碼 <h2>圖片上傳區</h2> <hr/> &l

ASP.NET MVC檔案下載Demo(檔案儲存在資料庫)

ASP.NET MVC檔案上傳下載Demo(檔案儲存在SQL Server資料庫中)如圖:後期考慮到安全問題,可以用MD5加密,生成加密資料庫連線字串,替換Web.config檔案中字串即可,如圖:如果

asp.net-html圖片

校驗 消息 data date map error ext 提交 ring 1,文件的上傳存在一個非常致命的文件,要是上傳病毒文件,可能會使你的系統崩潰 所以判斷文件的類型的非常重要的。 不能單獨與後綴名判斷,下面展示一種webform類型的上傳文件案例。 1,書寫htm

ASP.NET CORE的H5

圖片 tle core asp asp.net 修改 分享 c代碼 net 做的CORE項目中用到H5上傳,把以前的MVC代碼復制過來得修改一下才能用在.NET CORE中

圖片檔案示例

程式碼片段: //新增post @RequestMapping(method=RequestMethod.POST, value="/addPost") @ResponseBody public int addPost(Post post, MultipartFile file

檔案下載時,在form表單中設定屬性enctype=“multipart/form-data”的情況下,如何獲取表單提交的值?

一、問題描述 檔案上傳下載時,在form表單中設定屬性enctype=“multipart/form-data”的情況下,如何獲取表單提交的有關使用者資訊的值?(比如:textfield、radio等屬性中的值) 二、解決方法 1、情況一:沒有對user物件進行封裝 方法:

linux中檔案下載

windows篇 linux檔案下載到windows   sz命令   登入到linux伺服器使用 sz log.log 命令,彈出對話方塊選擇下載檔案的目錄,點選確定即可。   windows檔案上傳到linux   rz命令   登入到linux伺服器使用rz命令,彈出檔

.Net Core Web Api 女朋友的照片到微軟雲Azure Storage

前言 實現一個Web Api,把女朋友照片儲存到Azure雲的storage裡。 Image Upload Api 在對應的Api Controller裡,加上attribute: [Consumes("application/json", "multipart/form-data")] 然後定

linux壓縮和解壓縮命令,stp本地檔案下載和ssh連線與傳輸

linux 上檔案解壓縮指令 tar命令   解包:tar zxvf FileName.tar   打包:tar czvf FileName.tar DirName      解壓:tar zxvf FileName.tar.gz   壓縮:tar zcvf FileName.

springboot三種配置檔案下載大小的配置

配置檔案為application.yml格式: spring: http: multipart: enabled: true max-file-size: 30MB max-request-size: 30MB第二種: package com.haiyiso

SpringMVC篇:轉發與重定向、圖片檔案、Json(jackson)

注意: 專案:war 和 專案:war  exploded 兩者並不同,idea  執行 專案:war  exploded   <dependency> <groupId>org.

javaweb實現圖片檔案

圖片上傳到檔案中,可以直接上傳圖片到目錄中,也還可以將圖片檔名、檔案路徑寫入到資料庫中,也可以在程式中動態的建立檔案路徑。 參看:http://blog.csdn.net/lmdcszh/article/details/9201173 package com.ioif.wha.ima

struts2攔截器和檔案下載

一、攔截器(Interceptor) 攔截器是動態攔截Action呼叫的物件,攔截器將Action共用的行為獨立出來,在Action執行前後執行。這也就是我們所說的AOP,它是分散關注的程式設計方法,它將通用需求功能從不相關類之中分離出來;同時,能夠共享一個行為,一旦行為發生變化,不必修改很

關於layui圖片/檔案

一:常規使用   普通檔案上傳 (傳入伺服器一張圖片) 1.前臺程式碼: <!DOCTYPE html><html><head> <meta charset="utf-8" /> <link href="../layui/css/l