繁体   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