簡體   English   中英

如何在 wwwroot For ASP.NET MVC 中保存輸入圖像?

[英]How can i save an input image in the wwwroot For ASP.NET MVC?

所以我在視圖中有這個頁面:

    <div class="card">

        <div class="card-header">
            <h5>Scan a code</h5>
        </div>

        <div class="card-body">
            <form asp-controller="Scanner" asp-action="ScannerDone" method="post">

                <div class="mb-3">
                    <input asp-for=Photo type="file" accept="image/*" capture="camera">
                    
                </div>

                <div class="mb-3">
                    <label class="form-label">Content</label>
                    <input asp-for=Content type="text" class="form-control" />
                </div>

                <div class="mb-3">
                    <label class="form-label">Type</label>
                    <input asp-for=Type type="text" class="form-control" />
                </div>

                <div class="mb-3">
                    <button type="submit" class="btn btn-primary">Confirma</button>
                </div>

            </form>
        </div>

        <div class="card-footer">
        </div>

    </div>

</div>

我的問題是如何將圖像保存在 wwwroot 目錄中? 我一直試圖在互聯網上找到有關此的信息,但我發現它的一個命令名為:HttpPostedFileBase,它在這個新版本的 asp.net 中不起作用

由於這可能是 .NET Core,因此您可以使用IFormFile接口。

您的模型應相應更改:

public string Type { get; set; }
public string Content { get; set; }
public IFormFile File { get; set; }

然后,您可以使用類似這樣的方式編寫文件

string path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", File.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
    await File.CopyToAsync(stream);
}

這里有一個簡單的演示,介紹如何在 Asp.Net Core 中上傳文件並將其存儲在wwwroot中,您可以參考。

看法

<div>
    <h4>Single File Upload</h4>

  @* The type of form needs to be multipart/form-data *@

    <form asp-action="Index" enctype="multipart/form-data" method="post">
        <input type="file" name="file"/>
        <button type="submit">submit</button>
    </form>
</div>

控制器

public class HomeController : Controller
{
    
    private readonly IWebHostEnvironment _environment;

    public HomeController(IWebHostEnvironment environment)
    {
        
        _environment = environment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(IFormFile file)
    {
        
        string fileName = file.FileName;
        
        using (var fileStream = new FileStream(Path.Combine(_environment.WebRootPath,fileName), FileMode.Create))
        { 
           await file.CopyToAsync(fileStream);
        }
        
        
        //.........
        return RedirectToAction("Index");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM