#javascript #asp.net #ajax #iis #file-upload
#javascript #asp.net #ajax #iis #загрузка файла
Вопрос:
Я хочу иметь возможность загружать файл изображения (.pn&, .jp& и т.д.) На мой веб-сервер (под управлением IIS Server с ASPX), используя только HTML и AJAX.
Вот код:
<form id="personal-details-form" name="detailsfrm" method="POST" action="/ASPX/verifyPersonalDetails" enctype="multipart/form-data" novalidate&&t;
<label for="profile-pic-input"&&t;
<im& id="profile-pic" name="profilepic" class="profile-pic" src="/Media/user.pn&" onerror="document.profilepic.src = '/Media/user.pn&'" /&&t;
</label&&t;
<im& id="profile-pic-check" onerror="clearIma&e();" style="display: none;"/&&t;
<input id="profile-pic-input" name="pfpinput" type="file" accept="ima&e/pn&, ima&e/jpe&"
onchan&e="readIma&e(this);" style="display: none" /&&t;
<!-- more code that has nothin& to do with this question...--&&t;
// JS
function readIma&e(input) {
document.&etElementById("personal-details-error").innerHTML = "";
if (input.files amp;amp; input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#profile-pic').attr('src', e.tar&et.result);
$('#profile-pic-check').attr('src', e.tar&et.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function clearIma&e() {
document.&etElementById("personal-details-error").innerHTML = "Invalid ima&e.";
document.&etElementById("profile-pic-input").value = "";
}
$("#personal-details-form").submit(function (e) {
e.preventDefault();
$(".form-field").addClass("used");
document.&etElementById("personal-details-error").innerHTML = ""; // Remove errors
if (document.&etElementById("personal-details-form").checkValidity()) {
$.ajax({
type: "POST",
url: "../ASPX/verifyChan&eDetails.aspx",
data: $("#personal-details-form").serialize(),
success: function (data) {
},
});
}
});
if (Request.Files["pfpinput"] != null) {
HttpPostedFile MyFile = Request.Files["pfpinput"];
Response.Write(MyFile);
} else {
Response.Write("Nope!");
}
Я слышал, что enctype=»multipart/form-data» работает, но явно не в моем случае…
Что я должен сделать, чтобы мой AJAX-код мог загрузить файл изображения?
Комментарии:
1. Обратите внимание, что страница является HTML, а не ASPX. Я не могу выполнить какие-либо трюки с «runat» или «<asp:».
Ответ №1:
Оказывается, мне нужен был объект FormData, и добавить в него файл, наряду с другими вещами, поскольку я использовал AJAX.
var formData = new FormData(document.detailsfrm);
formData.append("pfpinput", document.detailsfrm.pfpinput.files[0]);