<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        .Net Core實現圖片文件上傳下載功能

        來源:懂視網 責編:小采 時間:2020-11-27 22:35:41
        文檔

        .Net Core實現圖片文件上傳下載功能

        .Net Core實現圖片文件上傳下載功能:當下.Net Core項目可是如雨后春筍一般發展起來,作為.Net大軍中的一員,我熱忱地擁抱了.Net Core并且積極使用其進行業務的開發,我們先介紹下.Net Core項目下實現文件上傳下載接口。 一、開發環境 毋庸置疑,宇宙第一IDE VisualStudio 2017
        推薦度:
        導讀.Net Core實現圖片文件上傳下載功能:當下.Net Core項目可是如雨后春筍一般發展起來,作為.Net大軍中的一員,我熱忱地擁抱了.Net Core并且積極使用其進行業務的開發,我們先介紹下.Net Core項目下實現文件上傳下載接口。 一、開發環境 毋庸置疑,宇宙第一IDE VisualStudio 2017

        當下.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('"');
        
         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="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圖片文件上傳的全部功能!

        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        .Net Core實現圖片文件上傳下載功能

        .Net Core實現圖片文件上傳下載功能:當下.Net Core項目可是如雨后春筍一般發展起來,作為.Net大軍中的一員,我熱忱地擁抱了.Net Core并且積極使用其進行業務的開發,我們先介紹下.Net Core項目下實現文件上傳下載接口。 一、開發環境 毋庸置疑,宇宙第一IDE VisualStudio 2017
        推薦度:
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 亚洲日韩国产精品第一页一区| 国产成人免费a在线视频app| 亚洲国产一成人久久精品| 美女被免费网站在线视频免费 | 丰满妇女做a级毛片免费观看| 毛片免费在线观看网站| 亚洲 欧洲 自拍 另类 校园| 国产福利在线免费| 国产亚洲精品bv在线观看| 久久久久国色AV免费观看性色 | 老司机午夜性生免费福利| 国产在线播放免费| 一级中文字幕免费乱码专区| 亚洲午夜爱爱香蕉片| 成人精品视频99在线观看免费| 国产亚洲真人做受在线观看| 久久久久免费看成人影片| 亚洲伊人久久大香线焦| 天天看免费高清影视| 思思久久99热免费精品6| 中文字幕精品亚洲无线码二区 | 亚洲国产综合精品一区在线播放| 一级做a爰片久久免费| 国产亚洲成av片在线观看| 18级成人毛片免费观看| 亚洲精品无AMM毛片| 亚洲成av人片在线观看天堂无码| 国产午夜成人免费看片无遮挡| 久久亚洲AV成人无码电影| 成年女人午夜毛片免费看| 免费在线人人电影网| 亚洲成Av人片乱码色午夜| 久九九精品免费视频| 极品色天使在线婷婷天堂亚洲| 久久精品亚洲福利| 69av免费视频| 一本到卡二卡三卡免费高| 久久亚洲精品成人无码网站| 日韩免费高清视频| 日本在线免费播放| 在线观看亚洲AV日韩A∨|