我是一个很好的后台开发人员,但在前台有一个很大的问题。所以,我有一个表格可以下载照片并将其发送到服务器。
<form name="Forma" id="photoForm" method="POST" enctype="multipart/form-data">
<input type="button" class="btn btn-secondary" name="btn_file" id="loadFileXml" value="Выбрать фото" onclick="document.getElementById('file').click();" />
<input type="file" id="file" style="display:none" name="photo" required accept="image/jpeg,image/png,image/gif " />
<button type="submit " class="btn btn-primary " hidden id="Test1">Проверить</button>
</form>
这是一个应该将数据发送到服务器的函数,用于获取 JSON 响应(我不确定,
var fileuploadinit = function(){
$('#file').change(function(){
var pathwithfilename = $('#file').val();
var filename = pathwithfilename.substring(12);
console.log(this.value);
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').removeAttr("hidden");
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(file.files[0]);
});
};
$("#imgInp").change(function() {
readURL(this);
});
$(document).ready(function () {
fileuploadinit();
});
$('#file').on('change', function() {
if (this.value) {
console.log("Оппа, выбрали файл!");
console.log(this.value);
// $('#Test1').attr("disabled", "false")
$("#Test1").removeAttr("hidden");
$('#Test3123').attr("src", this.value);
$("#info").removeAttr("hidden");
} else { // Если после выбранного тыкнули еще раз, но дальше cancel
console.log("Файл не выбран");
}
})
var button = document.getElementById("Test1")
button.onclick = handleButtonClick;
function handleButtonClick() {
alert("Вы нажали на кнопку");
var xhr = new XMLHttpRequest();
var url = "/api/upload";
xhr.open("Post", url, true);
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.setRequestHeader("Access-Control-Allow-Origin", "url/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 & xhr.status == 200){
var json = JSON.parse(xhr.responseText);
console.log(json.name);
}
};
var data = new FormData(photoForm)
xhr.send(data);
}
所以,我花了大约 2 天的时间,完全不知道如何从表单到服务器获取照片。我想,我真的什么都试过了。它有效,然后我在 html 表单方法中使用操作。