我已经尝试研究几乎所有内容,但没有找到修复代码的最终解决方案。如您在调试映像中所见,可以读取文件prop。在PHP中,print_r($_FILES); exit;
的结果是一个空数组。问题似乎是event.preventDefault();
。提交必须为prevent
,但仍必须生成文件。
$("#cardgeneratorForm").on("submit", function (event) {
event.preventDefault();
var artworkimageinput = $('#inputPicture').prop('files')[0];
var artworkimage = new FormData();
artworkimage.append('file', artworkimageinput);
$.ajax({
url: 'generatecard.php',
method: 'POST',
data: {
artworkimage: artworkimage,
},
cache: false,
processData: false,
contentType: false,
success : function(filename){
},
fail: function(){
}
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
move_uploaded_file($_FILES['file']['tmp_name'], 'artwork/' . $_FILES['file']['name']);
}
HTML
<form class="cardgeneratorForm" id="cardgeneratorForm" method="post" enctype="multipart/form-data" action="generatecard.php">
<div class="inputPicture-container custom-file col-12">
<input type="file" name="file" class="custom-file-input" accept='.jpg, .jpeg, .png, .webp' id="inputPicture" lang="en">
<label class="custom-file-label" for="inputPicture">Card Picture</label>
</div>
<button class="btn btn-primary btn-block btn-xs reset-button">
<span><i class="fas fa-redo"></i>Reset</span>
</button>
</form>
答案 0 :(得分:1)
这是您可以执行的操作。
$('#cardgeneratorForm').on('submit',function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
method:$(this).attr('method'), //dynamically getting the method of the form
url: $(this).attr('action'), //dynamically getting the action of the form
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
选择文件后立即开始上传(可选)
$("#inputPicture").on("change", function() {
$("#cardgeneratorForm").submit();
});
希望有帮助!
答案 1 :(得分:0)
使用ajaxform插件,您可以在此处找到示例 example ajaxform
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
// document.getElementsByName('userid')[0].value="{{ request.session.user_id }}";
$(".createnews").click(function(){
$("#formdata").ajaxForm({target: '#diagshow'});
});
});
</script>