在.Net 6 Razor页面中进行的Ajax文件上传在代码后台中发送Null。

huangapple go评论66阅读模式
英文:

Ajax file upload in .Net 6 Razor pages sends Null in the codebehind

问题

已经尝试过这个答案,但它没有起作用。所以正在寻求帮助。

我有一个.NET 6 Razor页面,我正在尝试从这里上传文件。

这是我的AjaxFileUpload.CSHtml

<h3>Ajax文件上传</h3>

<form method="post">
    <div class="mb-3">
        <label for="formFile" class="form-label">选择文件 1</label>
        <input class="form-control" type="file" id="formFile1">
        <br/>
        <button type="button" class="btn btn-info" onclick="UploadFile1ViaAjax()">上传文件 1</button>
        <span id="File1UploadStatus"></span>
    </div>
</form>

Ajax调用

<script>
function UploadFile1ViaAjax()
{          
   var file1 = $('#formFile1').prop("files")[0];
   
   var url = "/Employees/AjaxFileUpload?handler=UploadFile1";
   formData = new FormData();
   formData.append(file1.name, file1);

   alert("上传文件 1: " + file1.name);

   $.ajax({
        type: "POST",
        url: url,
        contentType: 'multipart/form-data',
        contentType: false,
        processData: false,            
        data: formData, 
        headers: {
            RequestVerificationToken:
                $('input:hidden[name="__RequestVerificationToken"]').val()
        },
        success: function (result) {
            alert("成功: " + JSON.stringify(result));
        },
        failure: function (result) {
            alert("失败");
        },
        error: function (result) {
            alert("错误");
        },
        }).done(function (result) {
                alert("Ajax调用完成。");
    });       
}
</script>

最后,这是AjaxFileUpload.CSHtml.cs中的代码后端方法:

public IActionResult OnPostUploadFile1(IFormFile formData)
{
    if (formData != null)
    {				
        return new ObjectResult(new { status = "success" });
    }
    return new ObjectResult(new { status = "fail" });
}

当我上传文件并单击按钮时,Ajax调用起作用,调试器会进入代码后端方法,但问题是,IFormFile对象始终为null。

为什么会发生这种情况?如何让IFormFile对象包含我上传的文件数据?

英文:

Already tried This Answer but it did not work. So seeking help.

I have a .Net 6 Razor page from where I am trying to upload a file.

Here is my AjaxFileUpload.CSHtml

&lt;h3&gt;Ajax File Upload&lt;/h3&gt;

 &lt;form method=&quot;post&quot;&gt;
    &lt;div class=&quot;mb-3&quot;&gt;
      &lt;label for=&quot;formFile&quot; class=&quot;form-label&quot;&gt;Select File 1&lt;/label&gt;
      &lt;input class=&quot;form-control&quot; type=&quot;file&quot; id=&quot;formFile1&quot;&gt;
      &lt;br/&gt;
      &lt;button type=&quot;button&quot; class=&quot;btn btn-info&quot; onclick=&quot;UploadFile1ViaAjax()&quot;&gt;Upload File 1&lt;/button&gt;
      &lt;span id=&quot;File1UploadStatus&quot;&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/form&gt;

The Ajax Call

&lt;script&gt;
            
function UploadFile1ViaAjax()
{          
   var file1 = $(&#39;#formFile1&#39;).prop(&quot;files&quot;)[0];
   
   var url = &quot;/Employees/AjaxFileUpload?handler=UploadFile1&quot;;
   formData = new FormData();
   formData.append(file1.name, file1);

   alert(&quot;Uploading file 1 : &quot; + file1.name);

   $.ajax({
        type: &quot;POST&quot;,
        url: url,
        contentType: &#39;multipart/form-data&#39;,
        contentType: false,
        processData: false,            
        data: formData, 
        headers: {
            RequestVerificationToken:
                $(&#39;input:hidden[name=&quot;__RequestVerificationToken&quot;]&#39;).val()
        },
        success: function (result) {
            alert(&quot;success: &quot; + JSON.stringify(result));
        },
        failure: function (result) {
            alert(&quot;failure&quot;);
        },
        error: function (result) {
            alert(&quot;error&quot;);
        },
        }).done(function (result) {
                alert(&quot;ajax call complete.&quot;);
    });       
    
}   

&lt;/script&gt;

Finally here is the code behind method AjaxFileUpload.CSHtml.cs

	public IActionResult OnPostUploadFile1(IFormFile formData)
	{
		if (formData != null)
		{				
			return new ObjectResult(new { status = &quot;success&quot; });
		}
		return new ObjectResult(new { status = &quot;fail&quot; });
	}

When I upload a file and click the button, The ajax call works and debugger is hit in the code behind method, but the problem is, the IFormFile object is always coming as null.

Why is this happening? How can I get the IFormFile object populated with file data that I am uploading ?

答案1

得分: 0

问题出在你的C#端点内的参数名称与ajax调用不匹配。尝试将formdata.append("fileName", file)设为,然后在你的端点中也将参数命名为fileName。否则,你应该通过提交表单或将文件上传为base64来上传它。

英文:

The problem is because the name of the parameter inside your C# endpoint doesn't match the ajax call. Try setting the formdata.append(&quot;fileName&quot;, file) and call the parameter in your endpoint fileName too. Other wise you should upload it either through submitting a form. Or uploading the file as base64

huangapple
  • 本文由 发表于 2023年5月26日 16:20:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定