Php 在确认提交到服务器之前预览带有图像的帖子
我有一个包含许多字段和图像的表单页面:Php 在确认提交到服务器之前预览带有图像的帖子,php,jquery,forms,post,preview,Php,Jquery,Forms,Post,Preview,我有一个包含许多字段和图像的表单页面: <form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data"> <input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFW
<form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data">
<input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFWNJTqNVYiP9">
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material" maxlength="30" style="width:30ch">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color" maxlength="10" style="width:20ch">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" maxlength="500">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input id="modelpic" name="image" type="file">
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show the preview of the image through javascript */
<div class="form-group">
<input id="AddBtn" class="btn btn-default" type="submit" value="Submit">
</form>
我认为这可能在数据类型或其他方面是错误的。为了防止表单提交,请使用
.on(“更改”,函数(事件){event.preventDefault().
ok,但我发布的javascript不会在按下提交按钮后被调用,而是在图像上传后被调用,以显示将要发布的图像。因此,我想我可以将动作部分保留在表单中,并使用$(“body”)创建一个新的JS;
…我需要的是在沿着图像提交表单后从表单中获取数据,显示预览,然后确认或中止。我已经有一段时间没有使用文件读取器了,但基本思想是,在提交字段之前,捕获提交事件,并使用js构建服务器输出的预览可能是继续提交表单,并将图像保存在服务器上的临时位置,然后重定向到预览页面,用户可以选择永久提交其更改或上载新图像。我尝试过这样做,但javascript以某种方式将表单提交搞砸,每个字段都被占用,而不是i法师。
$(document).ready(function() {
$('#modelpic').on("change", function () {
//shows image preview in DOM
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(this.files[0]); // read the local file
reader.onloadend = function(){ // show image in div
$('#imagePreview').show().html('<img id="theImage" src="' +this.result+ '" class="img-fluid" alt="Your Image" />');
}
}
})
});
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});