我正在尝试使用AJAX从部分视图上传图像文件,但它返回错误请求(400)错误。我搜索了SO答案,但它没有用。这是我的剧本:
$("#prodImgUpload").change(function() {
var formData = new FormData();
formData.append("file", $("#prodImgUpload")[0].files[0]);
console.log(formData.get("file"));
addAntiForgeryToken(formData);
$.ajax({
type: "POST",
url: "@Url.Action("UploadImage","Product",new{area="admin"})",
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
success: function(result) {
alert("Image uploaded successfully");
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
这是HTML:
<div class="upload-button">
<div class="label">Upload image</div>
<input asp-for="FileToUpload" id="prodImgUpload" name="FileToUpload"
type="file" accept="image/jpeg, image/png, image/jpg, image/bmp" />
</div>
它永远不会到达控制器。并且记住它在局部视图中。 这是我的控制者的行动:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UploadImage(IFormFile file)
{
if (file == null)
return Json(new { success = false, message = "No file uploaded" });
//do something with file.
}
答案 0 :(得分:0)
您未在AJAX请求中包含防伪令牌。有关如何使用防伪令牌处理AJAX请求,请参考documentation。基本上,您需要为AJAX请求添加标头:
$.ajax({
...
headers: {
"RequestVerificationToken": $('#RequestVerificationToken').val()
},
该值来自通过以下方式添加的隐藏输入:
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="hidden" id="RequestVerificationToken"
name="RequestVerificationToken" value="@GetAntiXsrfRequestToken()">