使用ajax或javascript上传php进程
我有表格和上传图像,工作正常,我想通过ajax或javascript处理它。如何使用javascript调整代码,使其不会刷新页面,只打印成功上传的消息。我们将非常感谢您的帮助。 我的代码如下: HTML:使用ajax或javascript上传php进程,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我有表格和上传图像,工作正常,我想通过ajax或javascript处理它。如何使用javascript调整代码,使其不会刷新页面,只打印成功上传的消息。我们将非常感谢您的帮助。 我的代码如下: HTML: <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="uploa
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action='upload.php'>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
error: function()
{
}
});
}));
});
</script>
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
我的JS:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action='upload.php'>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
error: function()
{
}
});
}));
});
</script>
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
$(文档).ready(函数(e){
$(“#uploadForm”)。在('submit',(函数(e)上{
e、 预防默认值();
$.ajax({
url:“upload.php”,
类型:“POST”,
数据:新表单数据(本),
contentType:false,
cache:false,
processData:false,
错误:函数()
{
}
});
}));
});
upload.php:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action='upload.php'>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
error: function()
{
}
});
}));
});
</script>
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
使用
$.ajax
的success
属性,这是一个函数,在请求成功后执行一些代码
例如:
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function() {
//Code on successful request
console.log('UPLOAD Successfully');
},
error: function()
{
}
});
假设您从php得到了正确的响应,这应该是很好的 懒得解释,哈哈 HTML
身体{
位置:相对位置;
}
.加载器{
位置:绝对位置;
宽度:100%;
身高:100%;
背景:rgba(0,0,0,0.42);
显示:无;
}
.loader.active{
显示:块;
}
已编辑
首先确保控制台日志中没有错误,
然后检查控制台日志上的所有内容
<script type="text/javascript">
$(document).ready(function () {
// Capture Form Submit Aaction
$("#uploadForm").on('submit',(function() {
// Show Loader Div when Button is click
$('.loader').addClass('active');
// Add Console Message confirming button is click
console.log('Start Ajax');
// Start Ajax Request
$.ajax({
type: 'POST',
// Place URL upload.php url here
url: 'http://yoursite.com/filesordir/upload.php',
// Never check your PHP data so I leave this lines below,
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
// If ajax response is success
success: function(data) {
// Hide the Loader Div
$('.loader').removeClass('active');
// Inser Ajax response to notice div
$('.notice').html( data );
// Add Console message
console.log('Ajax Success');
}
error: function( errorThrown ) {
// Hide the Loader Div
$('.loader').removeClass('active');
// Inser error message to notice div
$('.notice').html( errorThrown );
// Add Console message
console.log('Ajax Error');
}
});
//Edited this, have double ")".
});
});
</script>
$(文档).ready(函数(){
//捕获表单提交操作
$(“#uploadForm”)。在('submit',(function(){
//单击按钮时显示加载程序Div
$('.loader').addClass('active');
//单击“添加控制台消息确认”按钮
log('Start Ajax');
//启动Ajax请求
$.ajax({
键入:“POST”,
//将URL upload.php URL放在此处
网址:'http://yoursite.com/filesordir/upload.php',
//不要检查你的PHP数据,所以我在下面留下这行,
数据:新表单数据(本),
contentType:false,
cache:false,
processData:false,
//如果ajax响应成功
成功:函数(数据){
//隐藏Loader Div
$('.loader').removeClass('active');
//Inser Ajax对通知的响应div
$('.notice').html(数据);
//添加控制台消息
log('ajaxsuccess');
}
错误:函数(错误抛出){
//隐藏Loader Div
$('.loader').removeClass('active');
//通知div的插入错误消息
$('.notice').html(error抛出);
//添加控制台消息
log('Ajax错误');
}
});
//编辑此,有双“)”。
});
});
我有表单和上传的图像,效果很好,我想通过ajax或javascript进行处理。如何使用javascript调整代码,使其不会刷新页面,只打印成功上传的消息。
我为我的问题做了很多尝试,最后我成功了。答案如下:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data" action='upload.php'>
<input name="file" type="file" size="20" />
<input name="submit" type="submit" value="Upload" />
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
error: function()
{
}
});
}));
});
</script>
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
HTML
<script src="js/jquery.min.js"></script>
<script src="js/ajax-upload.js"></script>
<form id="frmUpload" action="" method="POST" name="default" class="form-horizontal">
<div class="img-upload">
<input type="file" name="file" id="file" class="user-image" required />
<div class="img-preview"></div>
<div class="upload-msg"></div>
</div>
<div class="form-actions">
<input type="submit" name="submit" value="Add Image Or Audio File" class="btn btn-primary">
<input type="reset" name="reset" value="Reset" class="btn">
</div>
</form>
ajax upload.js
$(document).ready(function (e) {
$("#frmUpload").on('submit',(function(e) {
e.preventDefault();
$(".upload-msg").text('Loading...');
$.ajax({
url: "process.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$(".upload-msg").html(data);
}
});
}
));
// Function to preview image after validation
$("#file").change(function() {
$(".upload-msg").empty();
var file = this.files[0];
var imagefile = file.type;
var imageTypes= ["image/jpeg","image/png","image/jpg","image/gif"];
if(imageTypes.indexOf(imagefile) == -1)
{
$(".upload-msg").html("<span class='msg-error'>Please Select A valid Image File</span><br /><span>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function(e){
$(".img-preview").html('<img src="' + e.target.result + '" />');
};
reader.readAsDataURL(this.files[0]);
}
});
});
$(文档).ready(函数(e){
$(“#frmUpload”)。关于('提交',(函数(e){
e、 预防默认值();
$(“.upload msg”).text('Loading…');
$.ajax({
url:“process.php”,//请求发送到的url
类型:“POST”,//要发送的请求类型,称为方法
数据:newformdata(this),//发送到服务器的数据,一组键/值对(即表单字段和值)
contentType:false,//向服务器发送数据时使用的内容类型。
cache:false,//无法请求缓存页面
processData:false,//若要发送DOMDocument或未处理的数据文件,将其设置为false
success:function(data)//请求成功时要调用的函数
{
$(“.upload msg”).html(数据);
}
});
}
));
//用于在验证后预览图像的函数
$(“#文件”).change(函数(){
$(“.upload msg”).empty();
var file=this.files[0];
var imagefile=file.type;
var imageTypes=[“image/jpeg”、“image/png”、“image/jpg”、“image/gif”];
if(imageTypes.indexOf(imagefile)=-1)
{
$(“.upload msg”).html(“请选择有效的图像文件
仅允许jpeg、jpg和png图像类型”);
返回false;
}
其他的
{
var reader=new FileReader();
reader.onload=函数(e){
$(“.img预览”).html(“”);
};
reader.readAsDataURL(this.files[0]);
}
});
});
process.php
<?php
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'uploads/'; //with trailing slash
//Set max file size in bytes
$max_size = 1000000;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "File is too big";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "Uploaded file is not a valid image";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "A file with this name already exists";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "No file uploaded";
return $out;
}
}
?>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_FILES["file"]["type"])){
$file = uploadFile('file', true, true);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
}
echo $message;
}
?>
看看通过ajax上传的过程有点复杂。查看本教程。有人能根据我的需要调整吗?它不是上传。当我选择一个图像然后按upload时,只需重置选择nothing elsewatch for this,var request={'upload':location.href+'upload.php',};检查网络,如果upload.php确实在运行,我假设您使用的是文件夹目录而不是index.html在浏览器中打开页面将整行url:request.upload,
更改为您的upload.php urlwell im使用index.php,然后是process upload.php和uplo