地狱的家伙我在网上搜索了一段时间用JavaScript上传文件我遇到了很好的网站,特别是这个https://developer.mozilla.org/en-US/docs/Web/API/FormData,所以我有这个脚本用ajax和jQuery上传一个图像给服务器所以我我想知道如何将其转换为jQuery结构。我不是document.getElementById
和.files[0]
结构的忠实粉丝。
这是我的代码
的index.php
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('button').click(function(){
var form_data = new FormData();
form_data.append('file', document.getElementById('file').files[0]);//<-Convert this section into a jQuery structure
//Success variable
var success= function(result){
$('.output').html(result);
}
//Error variable
var error= function(result){
alert(error);
}
//Request
$.ajax({
url:'x.php',
method:'POST',
data: form_data,
contentType: false,
processData: false,
success: success,
error: error
});
});
});
</script>
<input type='file' id='file'/>
<button>Send</button>
<div class='output'></div>
x.php
<?php
//Db credentials
$db_servername = 'localhost';
$db_username = 'sb';
$db_password = '1234';
$db_name = 'test';
//
$db_connect = new mysqli($db_servername, $db_username, $db_password, $db_name);
//Upload components structure
if($_FILES['file']['name'] != '')
{
$test = explode('.', $_FILES['file']['name']);
$ext = end($test);
$prefix= 'random';
$file_name = $prefix . uniqid() . '.' . $ext;
$directory = 'images/';
$location = $directory.$file_name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
}
//
$db_query= "INSERT INTO ajax_image_upload (image_name) VALUES ('$location')";
$db_result = $db_connect->query($db_query);
?>
<style>
#order{
display: inline-block;
margin-top: 50px;
}
#uploaded-image{
display: block;
width: 150px;
height: 150px;
}
#location-label{
display: inline-block;
font-weight: 600;
}
#location-value{
display: inline-block;
}
</style>
<p id='order'>Image 1</p>
<img id='uploaded-image' src='<?php echo $location; ?>'/>
<p id='location-label'>Location:</p><em id='location-value'><?php echo $location; ?></em>
答案 0 :(得分:0)
最简单的方法是将表单元素传递给FormData()
。没有必要使用append()
这样做
如果您在提交事件处理程序中执行此操作,则可以传入this
形式
<form id="myForm">
<input type='file' id='file'/>
<button>Send</button>
</form>
的jQuery
$(document).ready(function() {
$('myForm').submit(function(event) {
// prevent browser default submit process
event.preventDefault();
// "this" is the form element
var form_data = new FormData(this);
//Success variable
var success = function(result) {
$('.output').html(result);
}
//Error variable
var error = function(result) {
alert(error);
}
//Request
$.ajax({
url: 'x.php',
method: 'POST',
data: form_data,
contentType: false,
processData: false,
success: success,
error: error
});
});
});