繁体   English   中英

在 asp.net 核心客户端中使用 ajax 上传文件类型

[英]upload file type using ajax in asp.net core client

这是我的 html

<form enctype="multipart/form-data" class="needs-validation" id="formRequestLeave2">
     <div class="row form-group">
            <label class="col-md-4" for="File"><strong>Upload File</strong></label>
            <div class="col-md-7 form-control">
                 <input class="form-control custom-file-input" id="fileUpload" name="File" type="file" required>
                 <label class="custom-file-label">Choose File...</label>
            </div>
     </div>
</form>

这是我的 javascript

function Insert() {
    event.preventDefault();
    var obj = new Object();
    obj.EmployeeId = $("#employeeId2").val();
    obj.File = $("#fileUpload").val();
    manager = $("#managerName2").val()

    $.ajax({
        url: "/LeaveDetails/LeaveRequest",
        type: "POST",
        'data': obj,
})
}

这是我的 controller

public JsonResult LeaveRequest(LeaveRequestVM leaveRequestVM)
        {
            
            string uniqueFileName = null;
            if (leaveRequestVM.File != null)
            {
                string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "files");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + leaveRequestVM.File.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                leaveRequestVM.File.CopyTo(new FileStream(filePath, FileMode.Create));
            }
            leaveRequestVM.uniqueFileName = uniqueFileName;
          
            var result = repository.LeaveRequest(leaveRequestVM);
            return Json(result);
        }

我正在尝试使用 ajax 从我的视图将文件类型输入发送到我的 controller 但它出现了 null 我一直在尝试使用

contentType: false,
processData: false
   <form id="frmproduct" method="post" asp-antiforgery="true" class="row gy-1 pt-75" onsubmit="return false">
  <span class="btn btn-primary btn-sm btn-file">
 <input type="file" name="Image">
 </span>
</form>
<script>
frmproduct.onsubmit = async (e) => {
    e.preventDefault();
    if (!$("#frmproduct").valid())
        return false;
    let response = await fetch('/base/product/Create', {
        method: 'POST',
        body: new FormData(frmproduct)
    });

    let data = await response.json();

};
</script>

并从 Controller 获取文件

  [HttpPost, ValidateAntiForgeryToken]
        public async Task<JsonResult> Create(ProductViewModel model, CancellationToken cancellationToken)
        {
           var File= Request.Form.Files;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM