我知道如何通过 ajax 上传图片,但我想通过 jQuery 步骤上传图片。我尝试了多种方法,但它不起作用。如果有人这样做过,请帮助我。谢谢。
HTML
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
jQuery
if(currentIndex == 0)
{
var upload_doc = $("#upload_doc").val();
event.preventDefault();
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : { upload_doc : upload_doc, step1 : step1},
success: function(response) {
console.log(response);
}
});
}
最佳答案
按照这种方式上传图片,这样你就不需要 HTML form
。
将此代码添加到您的 mainpage.php
<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery('#uploadImage').on("click", function (e) {
var uploadedFile = new FormData();
uploadedFile.append('upload_doc', upload_doc.files[0]);
jQuery.ajax({
url: 'lab1.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: uploadedFile
});
});
</script>
然后为 upload.php 添加这个
<?php
// check record array
print_r($_FILES);
move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>