【发布时间】:2018-04-22 09:56:02
【问题描述】:
伙计们,我在网上搜索了一段时间关于使用 JavaScript 上传文件的问题,我遇到了一些不错的网站,尤其是这个 https://developer.mozilla.org/en-US/docs/Web/API/FormData,所以我有这个脚本可以使用 jQuery 将带有 ajax 的图像上传到服务器,所以我想知道如何将其转换为 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>
【问题讨论】:
-
它到底怎么不适合你?因为从您的 javascript 代码的外观来看,它看起来不错,正如 stackoverflow.com/a/21045034/614277 所建议的那样
-
对不起 abderranmane 我以为这是我已经看到的帖子我现在正在看它给我一点时间:-)。
-
对不起@AbderrahmaneTAHRIJOUTI 我以为我已经看到了那篇帖子,但显然我没有看到我需要更加小心无意重复的帖子,但感谢您将我链接到我的帖子没看到。
标签: javascript php jquery mysqli