在 ASP.NET Entity Framework 中上传文件的自动化编码方式

问题描述 投票:0回答:1

我对这个话题相当陌生。我可以通过从头开始编码所有内容,以某种方式使代码能够上传图片之类的文件,但是随着 ASP.NET MVC 和实体框架如今通过脚手架实现如此自动化,我认为必须有一种非常简单的方法将文件上传添加到脚手架实体框架解决方案。

有人知道这样的方法吗?

c# asp.net-mvc entity-framework asp.net-core file-upload
1个回答
0
投票

要在 ASP.NET Core 项目中上传文件,您应该首先在 View .cshtml 文件中插入一些行,如下所示(我更喜欢使用 javascript 代码来上传和发布文件,所以我也可以放置一个进度条):

<script type="text/javascript">

function uploadFile(currentForm) {

    let File1 = currentForm.querySelector("#File1").files[0];

    let fileName = currentForm.querySelector("#File1").value;
    fileName = fileName.substr(fileName.lastIndexOf("\\")).substr(1);
    currentForm.querySelector("#fileName").innerHTML = fileName;

    let data = new FormData();
    data.append("file", File1);

    let request = new XMLHttpRequest();
    let url = "/Home/UploadFile";
    let filePath = "";
    currentForm.querySelector("#progressBar").hidden = false;

    request.addEventListener("load", function (e) {
        filePath = request.responseText;            
        currentForm.querySelector("#fileLoaded").innerHTML = filePath;
    });

    request.upload.addEventListener("progress", function (e) {
        let percentual = (e.loaded / e.total) * 100;
        currentForm.querySelector("#progressBar").value = percentual;
    });

    request.open("POST", url);
    request.send(data);
}

</script>

<form id="Form1" method="post" enctype="application/x-www-form-urlencoded">    
    <!-- with this enctype the file will not be submitted with the form -->

    <input type="file" id="File1" name="File1" onchange="uploadFile(this.form)" style="display:none">
    <input type="button" value="Choose..." onclick="this.form.querySelector('#File1').click()">
    <span id="fileName"></span>                
    <progress hidden id="progressBar" value="0" max="100"></progress>
    <br />
    <label id="fileLoaded"> Uploaded file path: None </label>
    
</form>

之后,您需要一个操作(此处位于您的 HomeController 中),该操作使用 javascript 接收从网络发布的文件,将其保存在服务器文件夹中,并将其 URL 放入实体框架数据库上下文模型的属性中(即包含 UploadedFileURL 的 FileRow):

public class HomeController : Controller
{
    private readonly ApplicationDbContext _dbContext;
    private readonly IWebHostEnvironment _hostEnvironment;

    public HomeController(ApplicationDbContext dbContext, IWebHostEnvironment hostEnvironment)
    {
        _dbContext = dbContext;
        _hostEnvironment = hostEnvironment;
    }

    [HttpPost]
    public ContentResult UploadFile()
    {

        string filePath = "";
        string fileName = "";

        if (Request.Form.Files.Count > 0)
        {
            IFormFile file = Request.Form.Files[0];

            if (file != null && file.Length > 0)
            {
                fileName = Path.GetFileName(file.FileName);
                filePath = _hostEnvironment.WebRootPath + @"/Uploads/" + fileName;
                using (FileStream stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);                        
                }
                
                FileRow fileRow = new FileRow()
                {
                    UploadedFileURL = filePath
                };                                    
                _dbContext.Add(fileRow);
                _dbContext.SaveChanges();
            }
        }                                    
        return Content(filePath);
    }
}

文件将保存在 wwwroot/Uploads 文件夹中。

© www.soinside.com 2019 - 2024. All rights reserved.