aspnetcore上傳圖片也就是上傳檔案有兩種方式,一種是通過form-data,一種是binary,
先介紹第一種form-data:
該方式需要顯示指定一個IFormFile型別,該組件會動態通過打開一個windows視窗選擇檔案 及圖片,

postman演示如上,代碼如下:
[HttpPost] [AllowAnonymous] public IActionResult UploadFileByForm(IFormFile formFile) { var file = formFile; if (file == null) return JsonContent(new { status = "error" }.ToJson()); string path = $"/Upload/{Guid.NewGuid().ToString("N")}/{file.FileName}"; string physicPath = GetAbsolutePath($"~{path}"); string dir = Path.GetDirectoryName(physicPath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); using (FileStream fs = new FileStream(physicPath, FileMode.Create)) { file.CopyTo(fs); } string url = $"{_configuration["WebRootUrl"]}{path}"; var res = new { name = file.FileName, status = "done", thumbUrl = url, url = url }; return JsonContent(res.ToJson()); }
第二種通過binary

同樣是打開windows視窗選擇檔案,不過這里不需要引數顯式指定IFormFile
看代碼就明白了,這里通過請求背景關系的body來讀取位元組流,如果有提示不能同步讀取流的話,需要指定 services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true);現在都不用iis,所以不介紹了,
/// <summary> /// 上傳圖片 binary模式 /// </summary> /// <returns></returns> [HttpPost] [AllowAnonymous] public IActionResult UploadImage() { var request = HttpContext.Request; var stream = new BinaryReader(request.Body); var body = stream.ReadBytes(1024*1024*5); return File(body, @"image/jpeg"); }
aspnetcore7提供了如下的方式,通過指定本地檔案絕對地址來讀取位元組流,應該算是第二種方式吧,
代碼如下:參考:ASP.NET Core 7.0 的新增功能 | Microsoft Learn 需要引入包SixLabors.ImageSharp、SixLabors.ImageSharp.Formats.Jpeg
using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Processing; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/process-image/{strImage}", (string strImage, HttpContext http, CancellationToken token) => { http.Response.Headers.CacheControl = $"public,max-age={TimeSpan.FromHours(24).TotalSeconds}"; return Results.Stream(stream => ResizeImageAsync(strImage, stream, token), "image/jpeg"); }); async Task ResizeImageAsync(string strImage, Stream stream, CancellationToken token) { var strPath = $"wwwroot/img/{strImage}"; using var image = await Image.LoadAsync(strPath, token); int width = image.Width / 2; int height = image.Height / 2; image.Mutate(x =>x.Resize(width, height)); await image.SaveAsync(stream, JpegFormat.Instance, cancellationToken: token); }
總結:上傳檔案或圖片沒有什么難度,只不過注意輸出輸入的格式就行了,如果需要多檔案的話IFormFileCollection就行了, 這里不做介紹,可以看看微軟的官方檔案,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535109.html
標籤:.NET技术
上一篇:WPF輸入驗證提示
