【问题标题】:Trying to upload a file and display the files in a view尝试上传文件并在视图中显示文件
【发布时间】:2020-12-08 20:36:32
【问题描述】:

所以我正在尝试构建一个虚拟文件存储,我停留在我必须上传文件的部分,然后将它们显示在 File-s 视图中,以便用户可以下载、删除或查看它们。表单输入与文件上传一起位于模式框中。为了处理我使用@Html.BeginForm 的模态表单并处理我使用ajax 的文件上传。到目前为止,我已经实现的是我可以将文件上传到服务器文件夹,但我不知道如何将文件名和文件路径保存到 file-s 表的数据库中。我还需要有关如何在特定视图中显示这些文件的帮助。提前谢谢你。

HTML

<div class="modal-body">
                @using (Html.BeginForm("SaveRecord", "NgarkoDokument", FormMethod.Post, new { enctype = "mulptiple/form-data" }))
                {
                    <div class="form-group">
                        <label for="exampleFormControlSelect1">Lloji i dokumentit</label><br />
                        <select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>


                        <input type="button" title="Ngarko dokument" name="ngarko" value="Ngarko" id="uploadPop" class="btn btn-info col-md-3" onclick="document.getElementById('file').click();" />
                        <input type="file" onchange="javascript: updateList()" multiple="multiple" style="display:none;" id="file" name="postedFiles"/>
                        <div id="fileList"></div>
                    </div>
                    <br /><br />

                    <div class="form-group">
                        <label for="formGroupExampleInput">Fusha indeksimi</label> <br />
                        @*<input title="Indeksimi dokumentit" id="indeksimi" class="form-control col-md-3" type="text" name="indeksimi" placeholder="indeksimi" required />*@
                        @Html.TextBoxFor(a => a.Fusha_Indeksimit.Emri_Indeksimit, new { @class = "form-control", @placeholder = "indeksimi" })

                        @* <button title="Shto indeksim" id="modalPlus" type="submit" class="btn btn-info"><i class="glyphicon glyphicon-plus"></i></button>*@


                    </div>

                    <label for="formGroupExampleInput">Vendndodhja fizike e dokumentit</label><br>
                    <div id="zyraModal" class="form-group col-md-4">
                        @*<input title="Zyra fizike" id="zyra" class="form-control" type="text" name="zyra" placeholder="Zyra" />*@
                        @Html.TextBoxFor(a => a.Vendndodhja_fizike.Zyra, new { @class = "form-control", @placeholder
= "Zyra" })
                    </div>

                    <div class="form-group col-md-4">
                        @* <input title="Kutia fizike" id="kutia" class="form-control" type="number" name="kutia" placeholder="Nr i kutisë" />*@
                        @Html.TextBoxFor(a => a.Vendndodhja_fizike.Nr_Kutise, new { @class = "form-control", @placeholder = "Nr i kutisë" })
                    </div>

                    <div class="form-group col-md-4">
                        @* <input title="Rafti fizik" id="rafti" class="form-control" type="text" name="rafti" placeholder="Rafti" />*@
                        @Html.TextBoxFor(a => a.Vendndodhja_fizike.Rafti, new { @class = "form-control", @placeholder = "Rafti" })
                    </div>

                    <br /><br />

                    <div class="row" id="ruaj">
                        <button title="Ruaj dokumentin" type="submit" class="btn btn-success">Ruaj</button>
                    </div>
                }
            </div>

Ajax 脚本

<script type="text/javascript">
     

        $(document).ready(function () {
            $("#file").change(function () {
                  console.log("Image selected!");
                var formData = new FormData();
                var totalFiles = document.getElementById("file").files.length;
                for (var i = 0; i < totalFiles; i++) {
                    var file = document.getElementById("file").files[i];

                    formData.append("file", file);
                }
                $.ajax({
                    type: "POST",
                    url: '/UploadFile/Upload',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        alert('succes!!');
                    }
                });
            });
        });

    </script>

控制器

public ActionResult Dokument()
        {
             return View();
        }
  [HttpPost]
        public void Upload()
        {
            Dokumenti dok = new Dokumenti();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/File/"), fileName);
                file.SaveAs(path);
                }
        }

        public ActionResult SaveRecord(NgarkoDokument model)
        {
            try
            {
    
                Vendndodhja_Fizike vendndodhja = new Vendndodhja_Fizike();
                vendndodhja.Zyra = model.Vendndodhja_fizike.Zyra;
                vendndodhja.Rafti = model.Vendndodhja_fizike.Rafti;
                vendndodhja.Nr_Kutise = model.Vendndodhja_fizike.Nr_Kutise;

                db.Vendndodhja_Fizike.Add(vendndodhja);

                Fusha_Indeksimit indeksimi = new Fusha_Indeksimit();
                indeksimi.Emri_Indeksimit = model.Fusha_Indeksimit.Emri_Indeksimit;

                db.Fusha_Indeksimit.Add(indeksimi);

                Dokumenti dok = new Dokumenti();
                dok.Emer = model.Dokumenti.Emer;
 db.Dokumenti.Add(dok);

                db.SaveChanges();

                //int lastUserId = dok.UserID;
            }
            catch(Exception ex)
            {
                throw ex;
            }

            return RedirectToAction("Dokument");
        }
      
    }

【问题讨论】:

  • 是 ASP.NET MVC 项目,而不是 ASP.NET Core 项目?
  • 是的,它是一个 mvc 项目

标签: c# asp.net asp.net-mvc asp.net-core file-upload


【解决方案1】:

首先,您可能需要指定此项,因为您将 FormData 发送到您的控制器。例如:

public async Task CreateAsync([FromForm] CreateBookDto input)
{
...
}

上传文件时我关心很多事情,所以我的 js 文件有点长,但你可以得到适合你的:

$(function () {

var fileInput = document.getElementById('Book_CoverImageFile');
var file;

fileInput.addEventListener('change', function () {
    var showModal = true;
    
    file = fileInput.files[0];
    document.getElementById("choose-cover-image").innerHTML = file.name;

    var permittedExtensions = ["jpg", "jpeg", "png"]
    var fileExtension = $(this).val().split('.').pop();
    if (permittedExtensions.indexOf(fileExtension) === -1) {
        showModal = false;
        alert('This extension is not allowed')
        $('#Book_CoverImageFile').val('');
        $("#choose-cover-image").html("Choose a cover image...");
    }
    else if(file.size > 5*1024*1024) {
        showModal = false;
        alert('The file is too large');
    }
    
    var img = new Image();
    img.onload = function() {
        var sizes = {
            width:this.width,
            height: this.height
        };
        URL.revokeObjectURL(this.src);
        
        if (sizes.width > 1920 && sizes.height > 1080){
            alert('Height and Width must not exceed 1920*1080.')
             
           $('#Book_CoverImageFile').val('');
                    $("#choose-cover-image").html("Choose a cover image...");
       
        }
        
        var aspectRatio = sizes.width / sizes.height;
        aspectRatio = Number (aspectRatio.toFixed(1));
        
        if (aspectRatio !== 1.8){
            alert("The picture you uploaded is not in 16:9 aspect ratio!")
            $('#Book_CoverImageFile').val('');
            $("#choose-cover-image").html("Choose a cover image...");

        }
    }

    if(showModal === true) {
        readURL(this);
        $('#myModal').modal('show');
    }

    var objectURL = URL.createObjectURL(file);
    img.src = objectURL;
    
});

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#img-upload').attr('src', e.target.result);

        }

        reader.readAsDataURL(input.files[0]);
    }
}

$('form#CreateBookForm').submit(function (e) {
    e.preventDefault();
    
    var title = $('#Book_Title').val().trim();
         
    var formData = new FormData();

    formData.append("Title", title);
    formData.append("CoverImageFile", file);

    $.ajax({
        xhr: function() {
            var xhr = new window.XMLHttpRequest();

            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    percentComplete = parseInt(percentComplete * 100);
                    if(percentComplete !== 100){
                        $( '#Book_CoverImageFile' ).prop( "disabled", true );
                        $( '#Book_Title' ).prop( "disabled", true );
                        $( '#btnSubmit' ).prop( "disabled", true );
                    }
                }
            }, false);

            return xhr;
        },
        url: app.appPath + `api/app/Book`,
        data: formData,
        type: 'POST',
        contentType: false,
        processData: false,
        success: function(data){
            alert("The Book has been successfully submitted. It will be published after a review from the site admin.");
             window.location.href = "/books";
        },
        error: function (data) {
            alert(data.responseJSON.error.message);
        }
    });
});

这可以做很多事情,例如;文件允许扩展名控制、文件大小控制、检查文件是否超过 1920 * 1080 像素、文件是否有 16:9 的纵横比、发送文件时禁用表单元素等...

如果你真的关心安全,你应该这样做;

只接受允许的扩展:

  public class AllowedExtensionsAttribute : ValidationAttribute
  {
    private readonly string[] _extensions;
    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }

    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        if (value == null) // If uploading a file is optional on the form screen, it should be added == CanBeNul
        {
            return ValidationResult.Success;
        }
        
        var file = value as IFormFile;
        var extension = Path.GetExtension(file.FileName);
        
        if (file.Length > 0 && file != null)
        {
            if (!_extensions.Contains(extension.ToLower()))
            {
                return new ValidationResult(GetErrorMessage());
            }
        }

        return ValidationResult.Success;
    }

    public string GetErrorMessage()
    {
        return $"This extension is not allowed!";
    }
}

限制上传文件大小:

 public class MaxFileSizeAttribute : ValidationAttribute
 {
    private readonly int _maxFileSize;
    public MaxFileSizeAttribute(int maxFileSize)
    {
        _maxFileSize = maxFileSize;
    }

    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        if (value == null) // If uploading a file is optional on the form screen, it should be added == CanBeNull
        {
            return ValidationResult.Success;
        }
        
        var file = value as IFormFile;
        
        if (file.Length > 0)
        {
            if (file.Length > _maxFileSize)
            {
                return new ValidationResult(GetErrorMessage());
            }
        }

        return ValidationResult.Success;
    }

    public string GetErrorMessage()
    {
        return $"Maximum allowed file size is { _maxFileSize} bytes.";
    }
}

您必须将它们添加到 Dto:

   public class CreateBookDto
   {
      [Required]
      [StringLength(64)]
      public string Title { get; set; }

      [CanBeNull]
      [DataType(DataType.Upload)]
      [MaxFileSize(5*1024*1024)] // 5mb
      [AllowedExtensions(new string[] { ".jpg", ".png", ".jpeg" })]
      public IFormFile CoverImageFile { get; set; }
    }

最后,您的 HTML 文件应如下所示:

 <form method="post" id="CreateBookForm" asp-page="/Book/Create" enctype="multipart/form-data">
    <div class="form-group">
        <div class="custom-file">
            <input asp-for="Book.CoverImageFile" type="file" name="file" class="custom-file-input" id="Book_CoverImageFile"
                required="required">
            <label id="choose-cover-image" class="custom-file-label" for="customFile">Choose a cover image...</label>
            <small class="form-text text-muted">@L["CreateBookCoverInfo"].Value</small>
        </div>
    </div>

    ...

    <button id="btnSubmit" type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
            <div class="modal-content">
                    <div class="modal-body">
                            <img class="img-fluid" id="img-upload" alt=""/>
                    </div>
                    <div class="modal-footer">
                            <button type="button" class="btn btn-primary btn-block" data-dismiss="modal">Close</button>
                    </div>
            </div>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 2018-04-06
    • 2023-03-04
    • 2020-08-30
    • 2018-07-14
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    相关资源
    最近更新 更多