.net8 RC2がリリースされ、APIに対してComplex Formバインディング機能を導入しました。アップロードファイルタグは、Complex Formの一例です。以下は、単一ファイルアップロードの例です。
.csファイルは以下の通りです:
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles();
app.MapPost("/upload", ([FromForm] DocumentUpload document) => {
return Results.Ok();
}).DisableAntiforgery();
app.Run();
public class DocumentUpload {
public string Name { get; set; };
public string? Description { get; set; }
public IFormFile? Document { get; set; }
}
htmlファイルは以下の通りです:
<!DOCTYPE html><html>
<head>
<title>文件上传表单</title>
</head>
<body>
<h2>上传文件</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="name">名称:</label><input type="text" name="name" />
<br><br>
<label for="description">描述:</label>
<textarea row="3" name="description"></textarea>
<br><br>
<label for="file">文件:</label>
<input type="file" name="Document" id="file" accept=".jpg, .png, .pdf">
<br><br>
<input type="submit" name="submit" value="上传">
</form>
</body>
</html>
実行結果:
局部変数の確認:
複数の画像をアップロードしたい場合は、エンティティクラスのファイルリテラルタイプをIFormFileCollectionに変更すればよいです。
csコードは以下の通りです:
public class DocumentUpload {
public string Name { get; set; }
public string? Description { get; set; }
public IFormFileCollection? Documents { get; set; }
}
実行結果は以下の通りです:
局部変数の確認:
小さな機能ですが、開発体験に大きな影響を与え、簡素化され、直感的で使いやすいです。
(Translated by GPT)
元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247487181&idx=1&sn=f119574194e33bb2c509b9870a58bea4&chksm=9f0051e7a877d8f108763f9c95d640cae1e9a64310321cc28f79951ee17b2c24dd7b910d3434&token=2050451386&lang=zh_CN#rd