我正在创建文件上传脚本。
我想要做的是上传文件而不刷新页面
这是我的代码:
upload.php的
<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>
</body>
</html>
我想在AJAX上执行此操作,我已经搜索了一些示例,但我希望这更简单。
顺便说一句,是否可以在不使用任何插件或库的情况下运行?
答案 0 :(得分:1)
我设法为此找到了解决方案。我将PHP脚本与html分开并添加了一个javascript文件。我使用ajax调用PHP文件来上传文件。
这是我的代码;
<强>的index.php 强>
<html>
<head>
<style type="text/css">
.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px;
}
.uploads a, .uploads span{
display: block;
}
.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px;
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}
.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
for(x=0; x<data.succeeded.length; x = x+1){
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
</body>
</html>
<强> upload.php的强>
<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
<强> upload.js 强>
var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
无论如何,谢谢你的帮助。那些人很高兴得到赞赏。 谢谢!
答案 1 :(得分:0)
我认为在您的情况下,最简单的方法是将其放入iframe。我假设您在一个名为upload.php
的PHP文件中包含所有代码。你会得到这样的东西:
<?php
//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
echo '
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
<input type="file" name="file1[]" id="file1" multiple>
<input type="submit" value="Upload File">
</form>';
exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<!-- IFrame which loads the form !-->
<iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>
答案 2 :(得分:0)
Showing uploaded image after successful upload
你刚刚完成了这段代码,我已经给出了这类问题的答案