gpt4 book ai didi

php - 使用ajax和php上传文件

转载 作者:行者123 更新时间:2023-11-28 05:03:22 25 4
gpt4 key购买 nike

我想用ajax和php实现文件上传。我有一个表单输入标签。我想要输入标签的 onchange 事件,文件将上传到服务器,我将在 javascript 的变量中获取文件的路径!所以,我想留在同一页面上并上传文件,在 javascript 变量中获取文件路径。

任何伪代码、示例或教程将不胜感激。

最佳答案

演示网址:--

http://jquery.malsup.com/form/progress.html

您可以从此网址下载 jQuery 文件并在 html 中添加 <head>标记

http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js

http://malsup.github.com/jquery.form.js

试试这个:

这是我的 html 标记:

<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }

.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code>&lt;input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>

<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>

<div id="status"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});

})();
</script>

</body>
</html>

我的 php 代码:

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

关于php - 使用ajax和php上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11776351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com