0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.net8がもたらすComplex Formバインディング

Last updated at Posted at 2024-02-13

.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>

実行結果:
alt画像
局部変数の確認:
alt画像
複数の画像をアップロードしたい場合は、エンティティクラスのファイルリテラルタイプをIFormFileCollectionに変更すればよいです。
csコードは以下の通りです:

public class DocumentUpload {
    public string Name { get; set; }
    public string? Description { get; set; }
    public IFormFileCollection? Documents { get; set; }
}

実行結果は以下の通りです:
alt画像
局部変数の確認:
alt画像
小さな機能ですが、開発体験に大きな影響を与え、簡素化され、直感的で使いやすいです。

(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

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?