问题:
使用 jQuery 文件上传完成 .txt 文件的上传后,设置 session 变量并将用户重定向到不同的 PHP 页面。
HTML 代码(upload.php):
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
jQuery 代码(upload.php):
<script>
$(function () {
'use strict';
// Server-side upload handler:
var url = 'process.php';
$('#fileupload').fileupload({
url: url,
autoUpload: true,
acceptFileTypes: /(\.|\/)(txt)$/i,
maxFileSize: 5000000, // 5 MB
done: function (e, data) {
$(this).delay(2000, function(){
window.location = "explorer.php";
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
PHP上传脚本(process.php):
<?php
session_start();
$folder = 'upload';
if (!empty($_FILES))
{
// Set temporary name
$tmp = $_FILES['files']['tmp_name'];
// Set target path and file name
$target = $folder . '/' . $_FILES['files']['name'];
// Upload file to target folder
$status = move_uploaded_file($tmp, $target);
if ($status)
{
// Set session with txtfile name
$_SESSION['txtfile'] = $_FILES['files']['name'];
}
}
?>
所需输出:
- 文本文件应上传到文件夹/upload - 当前具有 chmod 777
- 文本文件名的 session 应分配给变量$_SESSION['txtfile']
- 上传到文件“explorer.php”后重定向用户
编辑:已解决。最终代码如上!
最佳答案
对于初学者...
请注意,您的输入
名称是files[]
并且具有属性multiple
。这意味着您正在向服务器发送一组文件,因此要在 php 中引用它们,您需要如下所示的内容:
$_FILES['文件']['名称'][0]
第一个文件。
此外,我发现 move_uploaded_file()
喜欢目标的完整路径,请尝试附加 $_SERVER['DOCUMENT_ROOT']
。
要将信息发送回 jQuery,您需要像这样使用 echo json_encode()
...
echo json_encode(array(
'status' => $status,
'message' => 'your message here'
));
在您的 done
函数中,可以像这样访问数据:
done: function(e, data){
console.log(data.status);
console.log(data.message);
}
关于javascript - 使用 jQuery 文件上传无法上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504612/