我在ASP.NET核心2.0的RAZOR页面上使用DropZone,并使用其他表单输入 -
DzDemo.cshtml页面 -
<form method="post" enctype="multipart/form-data">
<input type="text" id="Username" name="Username" />
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</form>
<div>
<button type="submit" id="submit-all"> upload </button>
</div>
JS: -
Dropzone.options.myDropzone = {
url: "/DzDemo?handler=Upload",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
// paramName: myParamName,
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on('sendingmultiple', function (data, xhr, formData) {
formData.append("UserName", $("#Username").val());
});
this.on('error',
function (file, response) {
console.log(response);
alert(response);
});
}
};
DzDemo.cshtml.cs页面: -
[HttpPost]
public IActionResult OnPostUpload()
{
var data = Request.Form; //This is
return Page();
}
但我从服务器得到400响应,我无法处理上传的文件服务器端。它也不会在服务器端热Upload
方法。请帮忙
答案 0 :(得分:1)
如果将dropzone.js与Razor Pages一起使用,将导致400的一件事是表单中缺少AntiforgeryToken。
这通常是自动注入的,但是删除_viewimports或其taghelpers可以防止这种情况。
要进行验证,只需在<form/>
元素内添加此行,或在调试控制台中查看错误消息。
@Html.AntiForgeryToken()
答案 1 :(得分:0)
在sendmultiple中添加此行,它将解决您的pb:
this.on('sendingmultiple', function (data, xhr, formData) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
});
答案 2 :(得分:0)
我通过设置$("#photo").change(function () {
var reader = new FileReader();
reader.onload = (e) => {
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
document.querySelector("#input").src = event.target.result;
imgElement.onload = function (evt) {
console.log(evt);
const canvas = document.createElement("canvas");
const MAX_WIDTH = 400;
const scaleSize = MAX_WIDTH / evt.target.width;
canvas.width = MAX_WIDTH;
canvas.height = evt.target.height * scaleSize;
const ctx = canvas.getContext("2d");
ctx.drawImage(evt.target, 0, 0, canvas.width, canvas.height);
const srcEncoded = ctx.canvas.toDataURL(evt.target, "image/jpeg");
document.querySelector("#output").src = srcEncoded;
reader.onload = () => srcEncoded = reader.result;
}
reader.readAsDataURL(this.files[0]);
});
选项使它正常工作
headers
当然,您需要在headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }
元素处或在页面中明确添加<form />