.Net Core 图片文件上传下载
當(dāng)下.Net Core項(xiàng)目可是如雨后春筍一般發(fā)展起來(lái),作為.Net大軍中的一員,我熱忱地?fù)肀Я?Net Core并且積極使用其進(jìn)行業(yè)務(wù)的開(kāi)發(fā),我們先介紹下.Net Core項(xiàng)目下實(shí)現(xiàn)文件上傳下載接口。
一、開(kāi)發(fā)環(huán)境
毋庸置疑,宇宙第一IDE VisualStudio 2017
二、項(xiàng)目結(jié)構(gòu)
?
FilesController 文件上傳下載控制器
PictureController 圖片上傳下載控制器
Return_Helper_DG 返回值幫助類
三、關(guān)鍵代碼
1、首先我們來(lái)看Startup.cs 這個(gè)是我們的程序啟動(dòng)配置類,在這里我們進(jìn)行一系列的配置。
跨域配置:
當(dāng)然跨域少不了dll的引用,我們使用Nuget引用相關(guān)的引用包
?服務(wù)器資源路徑置換,這樣可以防止客戶端猜測(cè)服務(wù)端文件路徑,制造一個(gè)虛擬的隱射進(jìn)行訪問(wèn),提高了安全性。
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類用戶設(shè)置一個(gè)統(tǒng)一的返回值反饋到客戶端
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是我們的文件上傳控制器接口,這里定義了對(duì)上傳的文件的接收操作,并且在控制器上啟用跨域配置
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));
? ? ? ? }
? ? }
}
在上述的代碼中,我們對(duì)上傳的文件的大小進(jìn)行了限制,并且對(duì)文件的大小進(jìn)行反饋。
4、PictureController 圖片上傳控制器接口,類似于文件,不過(guò)對(duì)上傳的圖片類型進(jìn)行了校驗(yàn)和限制
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));
? ? ? ? }
? ? }
}
到此,我們的文件圖片上傳代碼已經(jīng)全部完成,下面我們對(duì)文件上傳的客戶端進(jìn)行實(shí)現(xiàn)
四、客戶端的實(shí)現(xiàn)
?客戶端我們很簡(jiǎn)單地用jQuery Ajax的方式進(jìn)行圖片文件的提交,客戶端代碼的實(shí)現(xiàn):
<!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屬性可以選擇多項(xiàng)<br><br>
? ? ? ? ? ? ? ? <input type="button" id="btn_fileUpload" value="fileUpload">
? ? ? ? ? ? </form>
? ? ? ? </p>
? ? </article>
</body>
五、代碼測(cè)試
1.啟動(dòng)服務(wù)器
我們可以看到一個(gè)控制臺(tái)和一個(gè)web自動(dòng)啟動(dòng),并且web顯示默認(rèn)的Values控制器的請(qǐng)求返回值。
2.圖片上傳
我們使用ajax的方式進(jìn)行圖片的上傳操作,打開(kāi)測(cè)試web頁(yè)面,并且選擇圖片,點(diǎn)擊上傳,查看控制臺(tái)返回的結(jié)果:
可以看到,一張圖片上傳成功!
?輸入返回的地址,我們可以看到成功訪問(wèn)到了圖片,特別注意這里服務(wù)器路徑的改變:
多圖片上傳:
?
可見(jiàn),多圖片上傳沒(méi)有任何問(wèn)題!
同樣進(jìn)行文件上傳的測(cè)試:
?
?
同樣,文件上傳也沒(méi)有任何問(wèn)題!
六、總結(jié)
至此,我們已經(jīng)實(shí)現(xiàn)了預(yù)期的.Net Core圖片文件上傳的全部功能!
原文地址:http://www.cnblogs.com/qixiaoyizhan/p/7008976.html
.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺(tái)或掃描二維碼關(guān)注
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的.Net Core 图片文件上传下载的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: DllImport 自动选择x64或x8
- 下一篇: 谈一下我们是怎么做数据库单元测试(Dat