将 Jquery FileUploader 连接到我的 MySQL 数据库
Connect Jquery FileUploader To My MySQL Database
我正在尝试将 post 我网站的 post 表单上的 blueimp jquery 文件上传器连接到 mySQL 数据库,同时将 post 的文件上传到 post我网站的个人资料上的客户。我遵循了几个 stackflow 线程的说明以及使用了 blueimp 的 github sql 数据库集成说明。
我将文件上传到我的 GoDaddy 服务器上的指定文件路径,并且文件显示在列表中,但文件属性未存储在数据库文件中 table。如果我提交 post 所有内容都存储在我的数据库中,但使用 post.
上传的文件的详细信息除外
我当前的代码:
(来自 fileuploader 的 index.php 文件位于默认 server/php 路径中)
<?php
$options = array(
'delete_type' => 'POST',
'db_host' => 'localhost',
'db_user' => 'my database user',
'db_pass' => 'my database password',
'db_name' => 'my database name',
'db_table' => 'files'
);
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function initialize() {
$this->db = new mysqli(
$this->options['db_host'],
$this->options['db_user'],
$this->options['db_pass'],
$this->options['db_name']
);
parent::initialize();
$this->db->close();
}
protected function handle_form_data($file, $index) {
$file->title = @$_REQUEST['title'][$index];
$file->description = @$_REQUEST['description'][$index];
}
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = parent::handle_file_upload(
$uploaded_file, $name, $size, $type, $error, $index, $content_range
);
if (empty($file->error)) {
$sql = 'INSERT INTO `'.$this->options['db_table']
.'` (`name`, `size`, `type`, `title`, `description`)'
.' VALUES (?, ?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'sisss',
$file->name,
$file->size,
$file->type,
$file->title,
$file->description
);
$query->execute();
$file->id = $this->db->insert_id;
}
return $file;
}
protected function set_additional_file_properties($file) {
parent::set_additional_file_properties($file);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$sql = 'SELECT `id`, `type`, `title`, `description` FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $file->name);
$query->execute();
$query->bind_result(
$id,
$type,
$title,
$description
);
while ($query->fetch()) {
$file->id = $id;
$file->type = $type;
$file->title = $title;
$file->description = $description;
}
}
}
public function delete($print_response = true) {
$response = parent::delete(false);
foreach ($response as $name => $deleted) {
if ($deleted) {
$sql = 'DELETE FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $name);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}
}
$upload_handler = new UploadHandler();
(uploadhandler.php 来自上传者的文件。我按照 GoDaddy 的建议更改了服务器端口)
protected function get_full_url() {
$https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
return
($https ? 'https://' : 'http://').
(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
($https && $_SERVER['SERVER_PORT'] === 443 ||
$_SERVER['SERVER_PORT'] === 22 ? '' : ':'.$_SERVER['SERVER_PORT']))).
substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
}
(main.js 来自上传者的文件我将 url 从 server/php 更改为 server/php/index.php 正如我在一个线程中看到的那样,主机名改为托管我的网站,我也尝试了我的服务器托管的 IP。
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
url: 'server/php/index.php'
}).on('fileuploadsubmit', function (e, data) {
data.formData = data.context.find(':input').serializeArray();
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'wmlmusicguide.com') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//wmlmusicguide.com/admin/master_admin/server/php/index.php',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 999000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//wmlmusicguide.com/admin/master_admin/server/php/index.php',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
(也尝试结合另一个线程和开发人员的帮助)
/* global $, window */
/*jslint unparam: true, regexp: true */
/*global window, $ */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/index.php'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
$('#fileupload').fileupload({
url: 'server/php/index.php'
}).on('fileuploadsubmit', function (e, data) {
data.formData = data.context.find(':input').serializeArray();
});
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'GoDaddy server IP' ? '//wmlmusicguide.com/admin/master_admin/server/php/index.php' : '../../server/php/',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|mp3|ogg|mp4)$/i,
maxFileSize: 26214400,
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
(上传者所在的 post 页面的后端)
...
<!-- The file upload form used as target for the file upload widget -->
<form id="fileupload" action="//jquery-file-upload.appspot.com/" method="POST" enctype="multipart/form-data">
<!-- Redirect browsers with JavaScript disabled to the origin page -->
<noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript>
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="fileupload-buttonbar">
<div class="fileupload-buttons">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="fileinput-button">
<span>Add files...</span>
<input type="file" name="files[]" multiple>
</span>
<button type="submit" class="start">Start upload</button>
<button type="reset" class="cancel">Cancel upload</button>
<button type="button" class="delete">Delete</button>
<input type="checkbox" class="toggle">
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="fileupload-progress fade" style="display:none">
<!-- The global progress bar -->
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
<!-- The extended global progress state -->
<div class="progress-extended"> </div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation"><tbody class="files"></tbody></table>
</form>
<br>
<!-- The blueimp Gallery widget -->
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
<div class="slides"></div>
<h3 class="title"></h3>
<a class="prev">‹</a>
<a class="next">›</a>
<a class="close">×</a>
<a class="play-pause"></a>
<ol class="indicator"></ol>
</div>
<div class="clear"> </div>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="content-table">
<tr>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowleft.jpg" width="20" height="300" alt="" /></th>
<th class="topleft"></th>
<td id="tbl-border-top"> </td>
<th class="topright"></th>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowright.jpg" width="20" height="300" alt="" /></th>
</tr>
<tr>
<td id="tbl-border-left"></td>
<td>
<!-- start content-table-inner ...... START -->
<div id="content-table-inner">
<!-- start table-content -->
<div id="table-content" style="border:0px solid red">
<form id="postForm" action="postcontroller.php" method="post" enctype="multipart/form-data">
<!-- start id-form -->
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Post Title:</th>
<td><input type="text" class="inp-form required" name="name" value="<?php if(isset($data['row']['name'])) echo $data['row']['name']; ?>" /></td>
</tr>
<tr>
<th valign="top">Description:</th>
<td><textarea class="form-textarea" cols="" rows="" name="details"><?php if(isset($data['row']['details'])) echo $data['row']['details']; ?></textarea></td>
<td></td>
</tr>
<tr>
<th valign="top">URL:</th>
<td><input type="url" class="inp-form" name="postlink" value="<?php if(isset($data['row']['post_link'])) echo $data['row']['post_link']; ?>" /></td>
</tr>
<tr>
<th valign="top">Client:</th>
<td>
<?php
$host_name = "localhost";
$database = "wmy database name";
$username = "my username";
$password = "my password";
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Select all artists (clients) and order by name //
$sql="SELECT aname FROM tbl_music_artists ORDER BY aname";
// multi-select dropdown - select which artists (clients) receive posts //
?>
<select name="userids[]" class="chosen-select" data-placeholder="Choose a Client..." style="width:350px;" multiple>
<?php
foreach ($dbo->query($sql) as $row){
echo "<option value=$row[id]>$row[aname]</option>";
}
?>
</select>
</td>
</tr>
<tr>
<th valign="top">Category:</th>
<td>
<select class="chosen-select" name="category">
<option value="">Select option</option>
<option value="music" <?php if(isset($data['row']['category']) && $data['row']['category'] == 'music') echo "selected"; ?>>Music</option>
<option value="video" <?php if(isset($data['row']['category']) && $data['row']['category'] == 'video') echo "selected"; ?>>Video</option>
</select>
</td>
</tr>
<tr>
<th valign="top">Status:</th>
<td>
<select class="chosen-select" name="status">
<option value="1" <?php if(isset($data['row']['status']) && $data['row']['status'] == '1') echo "selected"; ?>>Active</option>
<option value="0" <?php if(isset($data['row']['status']) && $data['row']['status'] == '0') echo "selected"; ?>>Inactive</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="" class="form-submit" />
<input id="restform" class="form-reset">
<a href="post.php" class="form-cancel">Cancel</a>
</td>
<td> </td>
<td> </td>
</tr>
</table>
<input type="hidden" name="form" value="<?php echo $data['formStatus'] ?>" />
<input type="hidden" name="id" id="id" value="<?php echo $data['id'] ?>" />
</form>
</td>
</tr>
</table>
</div>
</div>
<div class="clear"> </div>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td>
<span class="preview"></span>
</td>
<td>
<p class="name">{%=file.name%}</p>
<strong class="error"></strong>
</td>
<td>
<p class="size">Processing...</p>
<div class="progress"></div>
</td>
<td>
{% if (!i && !o.options.autoUpload) { %}
<button class="start" disabled>Start</button>
{% } %}
{% if (!i) { %}
<button class="cancel">Cancel</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
<td>
<span class="preview">
{% if (file.thumbnailUrl) { %}
<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
{% } %}
</span>
</td>
<td>
<p class="name">
<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
</p>
{% if (file.error) { %}
<div><span class="error">Error</span> {%=file.error%}</div>
{% } %}
</td>
<td>
<span class="size">{%=o.formatFileSize(file.size)%}</span>
</td>
<td>
<button class="delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>Delete</button>
<input type="checkbox" name="delete" value="1" class="toggle">
</td>
</tr>
{% } %}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<!-- The Templates plugin is included to render the upload/download listings -->
<script src="//blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="//blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="//blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<!-- blueimp Gallery script -->
<script src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="../js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="../js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="../js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="../js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="../js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="../js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="../js/jquery.fileupload-validate.js"></script>
<!-- The File Upload user interface plugin -->
<script src="../js/jquery.fileupload-ui.js"></script>
<!-- The File Upload jQuery UI plugin -->
<script src="../js/jquery.fileupload-jquery-ui.js"></script>
<!-- The main application script -->
<script src="../js/main.js"></script>
<script>
// Initialize the jQuery UI theme switcher:
$('#theme-switcher').change(function () {
var theme = $('#theme');
theme.prop(
'href',
theme.prop('href').replace(
/[\w\-]+\/jquery-ui.css/,
$(this).val() + '/jquery-ui.css'
)
);
});
// Post Form Validate
$(document).ready(function () {
$('#postForm').validate({
errorElement: "div",
rules: {
name: { required: true },
details: { required: true },
category: { required: true }
}
});
$('#restform').click(function(){
$('#postForm')[0].reset();
});
});
// Chosen multi-select
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
(前端连接到我的 post 页面)
<?php
include('includes/inc.php');
include("includes/classes/class.post.php");
include("includes/classes/class.artist.php");
$post = new Post();
//new
$data['formStatus'] = 'new';
$data['id'] = 0;
$data['aid'] = 0;
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = isset($_GET['id']) ? $_GET['id'] : 0;
$checkRow = $post->get_row($id);
if(is_array($checkRow)){
$data['formStatus'] = 'edit';
$data['row'] = $checkRow;
$data['id'] = $checkRow['id'];
$data['post'] = checkImagexists('../../uploads/', 'post_' . $checkRow['id']);
}
}
layout('post_form', $data);
?>
(post我第一次尝试从文件上传器获取文件的控制器文件)
<?php
session_start();
include("includes/functions.php");
include("includes/classes/class.post.php");
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//Get newly uploaded files from /uploads/server/php
$files = $_POST['files'];
if(!empty($files)){
//Rename all files in the upload server php directory to post_id format
//Move files to upload directory
foreach ($files as $file){
if ($handle = opendir('../../uploads/server/php/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = '../../uploads/' . 'post_' . $_POST['id'] . '_' . $file;
$oldName = '../../uploads/client/files/' . $file;
rename($oldName, $newName);
}
}
closedir($handle);
}
}
$client_cat = isset($_POST['userids']) ? $_POST['userids'] : array();
$user_id = $_SESSION['user_id'];
// Client post to own page
$post = new post();
$arrData = array();
$arrData['name'] = addslashes(ucwords($_POST['name']));
$arrData['details'] = addslashes($_POST['details']);
$arrData['post_link'] = $_POST['post_link'];
$arrData['status'] = addslashes($_POST['status']);
$arrData['type'] = $_FILES['image']['type'];
$arrData['category'] = addslashes($_POST['category']);
if(empty($_POST['id'])){
$arrData['user_id'] = $user_id;
$arrData['added_date'] = date('Y-m-d H:i:s');
$insert = $post->add($arrData);
if($insert){
$client_prop = array_merge($client_cat, $files);
$client->add_prop($client_prop, $insert, 'artist');
}
}
}
else
{
echo "Invalid file";
}
header('Location: post.php?act=' . $_SESSION['insert_post']);
?>
screenshot of index.php for the uploader where i tried to make the connection to my database as instructed
screenshot of mysql post & files table, the fields that were created as instructed
根据我在 Loki 发布的另一个帖子中遇到的响应,我能够在 blueimp jQuery 文件上传器和 mySQL 数据库之间建立连接.如果您不知道自己在做什么,使用 not so helpful 集成发布在 blueimp github 上不是解决方案。我必须将两者结合使用才能发挥作用。
感谢Loki和Whosebug平台帮我解决了这个问题
screenshot of my post page before/after file upload, index.php (file from the jquery file uploader) files print report, and mysql files table after file uploading
我正在尝试将 post 我网站的 post 表单上的 blueimp jquery 文件上传器连接到 mySQL 数据库,同时将 post 的文件上传到 post我网站的个人资料上的客户。我遵循了几个 stackflow 线程的说明以及使用了 blueimp 的 github sql 数据库集成说明。
我将文件上传到我的 GoDaddy 服务器上的指定文件路径,并且文件显示在列表中,但文件属性未存储在数据库文件中 table。如果我提交 post 所有内容都存储在我的数据库中,但使用 post.
上传的文件的详细信息除外我当前的代码: (来自 fileuploader 的 index.php 文件位于默认 server/php 路径中)
<?php
$options = array(
'delete_type' => 'POST',
'db_host' => 'localhost',
'db_user' => 'my database user',
'db_pass' => 'my database password',
'db_name' => 'my database name',
'db_table' => 'files'
);
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function initialize() {
$this->db = new mysqli(
$this->options['db_host'],
$this->options['db_user'],
$this->options['db_pass'],
$this->options['db_name']
);
parent::initialize();
$this->db->close();
}
protected function handle_form_data($file, $index) {
$file->title = @$_REQUEST['title'][$index];
$file->description = @$_REQUEST['description'][$index];
}
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = parent::handle_file_upload(
$uploaded_file, $name, $size, $type, $error, $index, $content_range
);
if (empty($file->error)) {
$sql = 'INSERT INTO `'.$this->options['db_table']
.'` (`name`, `size`, `type`, `title`, `description`)'
.' VALUES (?, ?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'sisss',
$file->name,
$file->size,
$file->type,
$file->title,
$file->description
);
$query->execute();
$file->id = $this->db->insert_id;
}
return $file;
}
protected function set_additional_file_properties($file) {
parent::set_additional_file_properties($file);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$sql = 'SELECT `id`, `type`, `title`, `description` FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $file->name);
$query->execute();
$query->bind_result(
$id,
$type,
$title,
$description
);
while ($query->fetch()) {
$file->id = $id;
$file->type = $type;
$file->title = $title;
$file->description = $description;
}
}
}
public function delete($print_response = true) {
$response = parent::delete(false);
foreach ($response as $name => $deleted) {
if ($deleted) {
$sql = 'DELETE FROM `'
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('s', $name);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}
}
$upload_handler = new UploadHandler();
(uploadhandler.php 来自上传者的文件。我按照 GoDaddy 的建议更改了服务器端口)
protected function get_full_url() {
$https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
return
($https ? 'https://' : 'http://').
(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
($https && $_SERVER['SERVER_PORT'] === 443 ||
$_SERVER['SERVER_PORT'] === 22 ? '' : ':'.$_SERVER['SERVER_PORT']))).
substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
}
(main.js 来自上传者的文件我将 url 从 server/php 更改为 server/php/index.php 正如我在一个线程中看到的那样,主机名改为托管我的网站,我也尝试了我的服务器托管的 IP。
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
url: 'server/php/index.php'
}).on('fileuploadsubmit', function (e, data) {
data.formData = data.context.find(':input').serializeArray();
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'wmlmusicguide.com') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//wmlmusicguide.com/admin/master_admin/server/php/index.php',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 999000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//wmlmusicguide.com/admin/master_admin/server/php/index.php',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
(也尝试结合另一个线程和开发人员的帮助)
/* global $, window */
/*jslint unparam: true, regexp: true */
/*global window, $ */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/index.php'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
$('#fileupload').fileupload({
url: 'server/php/index.php'
}).on('fileuploadsubmit', function (e, data) {
data.formData = data.context.find(':input').serializeArray();
});
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'GoDaddy server IP' ? '//wmlmusicguide.com/admin/master_admin/server/php/index.php' : '../../server/php/',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|mp3|ogg|mp4)$/i,
maxFileSize: 26214400,
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
(上传者所在的 post 页面的后端)
...
<!-- The file upload form used as target for the file upload widget -->
<form id="fileupload" action="//jquery-file-upload.appspot.com/" method="POST" enctype="multipart/form-data">
<!-- Redirect browsers with JavaScript disabled to the origin page -->
<noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript>
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="fileupload-buttonbar">
<div class="fileupload-buttons">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="fileinput-button">
<span>Add files...</span>
<input type="file" name="files[]" multiple>
</span>
<button type="submit" class="start">Start upload</button>
<button type="reset" class="cancel">Cancel upload</button>
<button type="button" class="delete">Delete</button>
<input type="checkbox" class="toggle">
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="fileupload-progress fade" style="display:none">
<!-- The global progress bar -->
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
<!-- The extended global progress state -->
<div class="progress-extended"> </div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation"><tbody class="files"></tbody></table>
</form>
<br>
<!-- The blueimp Gallery widget -->
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
<div class="slides"></div>
<h3 class="title"></h3>
<a class="prev">‹</a>
<a class="next">›</a>
<a class="close">×</a>
<a class="play-pause"></a>
<ol class="indicator"></ol>
</div>
<div class="clear"> </div>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="content-table">
<tr>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowleft.jpg" width="20" height="300" alt="" /></th>
<th class="topleft"></th>
<td id="tbl-border-top"> </td>
<th class="topright"></th>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowright.jpg" width="20" height="300" alt="" /></th>
</tr>
<tr>
<td id="tbl-border-left"></td>
<td>
<!-- start content-table-inner ...... START -->
<div id="content-table-inner">
<!-- start table-content -->
<div id="table-content" style="border:0px solid red">
<form id="postForm" action="postcontroller.php" method="post" enctype="multipart/form-data">
<!-- start id-form -->
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Post Title:</th>
<td><input type="text" class="inp-form required" name="name" value="<?php if(isset($data['row']['name'])) echo $data['row']['name']; ?>" /></td>
</tr>
<tr>
<th valign="top">Description:</th>
<td><textarea class="form-textarea" cols="" rows="" name="details"><?php if(isset($data['row']['details'])) echo $data['row']['details']; ?></textarea></td>
<td></td>
</tr>
<tr>
<th valign="top">URL:</th>
<td><input type="url" class="inp-form" name="postlink" value="<?php if(isset($data['row']['post_link'])) echo $data['row']['post_link']; ?>" /></td>
</tr>
<tr>
<th valign="top">Client:</th>
<td>
<?php
$host_name = "localhost";
$database = "wmy database name";
$username = "my username";
$password = "my password";
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Select all artists (clients) and order by name //
$sql="SELECT aname FROM tbl_music_artists ORDER BY aname";
// multi-select dropdown - select which artists (clients) receive posts //
?>
<select name="userids[]" class="chosen-select" data-placeholder="Choose a Client..." style="width:350px;" multiple>
<?php
foreach ($dbo->query($sql) as $row){
echo "<option value=$row[id]>$row[aname]</option>";
}
?>
</select>
</td>
</tr>
<tr>
<th valign="top">Category:</th>
<td>
<select class="chosen-select" name="category">
<option value="">Select option</option>
<option value="music" <?php if(isset($data['row']['category']) && $data['row']['category'] == 'music') echo "selected"; ?>>Music</option>
<option value="video" <?php if(isset($data['row']['category']) && $data['row']['category'] == 'video') echo "selected"; ?>>Video</option>
</select>
</td>
</tr>
<tr>
<th valign="top">Status:</th>
<td>
<select class="chosen-select" name="status">
<option value="1" <?php if(isset($data['row']['status']) && $data['row']['status'] == '1') echo "selected"; ?>>Active</option>
<option value="0" <?php if(isset($data['row']['status']) && $data['row']['status'] == '0') echo "selected"; ?>>Inactive</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="" class="form-submit" />
<input id="restform" class="form-reset">
<a href="post.php" class="form-cancel">Cancel</a>
</td>
<td> </td>
<td> </td>
</tr>
</table>
<input type="hidden" name="form" value="<?php echo $data['formStatus'] ?>" />
<input type="hidden" name="id" id="id" value="<?php echo $data['id'] ?>" />
</form>
</td>
</tr>
</table>
</div>
</div>
<div class="clear"> </div>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td>
<span class="preview"></span>
</td>
<td>
<p class="name">{%=file.name%}</p>
<strong class="error"></strong>
</td>
<td>
<p class="size">Processing...</p>
<div class="progress"></div>
</td>
<td>
{% if (!i && !o.options.autoUpload) { %}
<button class="start" disabled>Start</button>
{% } %}
{% if (!i) { %}
<button class="cancel">Cancel</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
<td>
<span class="preview">
{% if (file.thumbnailUrl) { %}
<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
{% } %}
</span>
</td>
<td>
<p class="name">
<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
</p>
{% if (file.error) { %}
<div><span class="error">Error</span> {%=file.error%}</div>
{% } %}
</td>
<td>
<span class="size">{%=o.formatFileSize(file.size)%}</span>
</td>
<td>
<button class="delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>Delete</button>
<input type="checkbox" name="delete" value="1" class="toggle">
</td>
</tr>
{% } %}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<!-- The Templates plugin is included to render the upload/download listings -->
<script src="//blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="//blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="//blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<!-- blueimp Gallery script -->
<script src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="../js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="../js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="../js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="../js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="../js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="../js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="../js/jquery.fileupload-validate.js"></script>
<!-- The File Upload user interface plugin -->
<script src="../js/jquery.fileupload-ui.js"></script>
<!-- The File Upload jQuery UI plugin -->
<script src="../js/jquery.fileupload-jquery-ui.js"></script>
<!-- The main application script -->
<script src="../js/main.js"></script>
<script>
// Initialize the jQuery UI theme switcher:
$('#theme-switcher').change(function () {
var theme = $('#theme');
theme.prop(
'href',
theme.prop('href').replace(
/[\w\-]+\/jquery-ui.css/,
$(this).val() + '/jquery-ui.css'
)
);
});
// Post Form Validate
$(document).ready(function () {
$('#postForm').validate({
errorElement: "div",
rules: {
name: { required: true },
details: { required: true },
category: { required: true }
}
});
$('#restform').click(function(){
$('#postForm')[0].reset();
});
});
// Chosen multi-select
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
</script>
(前端连接到我的 post 页面)
<?php
include('includes/inc.php');
include("includes/classes/class.post.php");
include("includes/classes/class.artist.php");
$post = new Post();
//new
$data['formStatus'] = 'new';
$data['id'] = 0;
$data['aid'] = 0;
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = isset($_GET['id']) ? $_GET['id'] : 0;
$checkRow = $post->get_row($id);
if(is_array($checkRow)){
$data['formStatus'] = 'edit';
$data['row'] = $checkRow;
$data['id'] = $checkRow['id'];
$data['post'] = checkImagexists('../../uploads/', 'post_' . $checkRow['id']);
}
}
layout('post_form', $data);
?>
(post我第一次尝试从文件上传器获取文件的控制器文件)
<?php
session_start();
include("includes/functions.php");
include("includes/classes/class.post.php");
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//Get newly uploaded files from /uploads/server/php
$files = $_POST['files'];
if(!empty($files)){
//Rename all files in the upload server php directory to post_id format
//Move files to upload directory
foreach ($files as $file){
if ($handle = opendir('../../uploads/server/php/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = '../../uploads/' . 'post_' . $_POST['id'] . '_' . $file;
$oldName = '../../uploads/client/files/' . $file;
rename($oldName, $newName);
}
}
closedir($handle);
}
}
$client_cat = isset($_POST['userids']) ? $_POST['userids'] : array();
$user_id = $_SESSION['user_id'];
// Client post to own page
$post = new post();
$arrData = array();
$arrData['name'] = addslashes(ucwords($_POST['name']));
$arrData['details'] = addslashes($_POST['details']);
$arrData['post_link'] = $_POST['post_link'];
$arrData['status'] = addslashes($_POST['status']);
$arrData['type'] = $_FILES['image']['type'];
$arrData['category'] = addslashes($_POST['category']);
if(empty($_POST['id'])){
$arrData['user_id'] = $user_id;
$arrData['added_date'] = date('Y-m-d H:i:s');
$insert = $post->add($arrData);
if($insert){
$client_prop = array_merge($client_cat, $files);
$client->add_prop($client_prop, $insert, 'artist');
}
}
}
else
{
echo "Invalid file";
}
header('Location: post.php?act=' . $_SESSION['insert_post']);
?>
screenshot of index.php for the uploader where i tried to make the connection to my database as instructed screenshot of mysql post & files table, the fields that were created as instructed
根据我在 Loki 发布的另一个帖子中遇到的响应,我能够在 blueimp jQuery 文件上传器和 mySQL 数据库之间建立连接.如果您不知道自己在做什么,使用 not so helpful 集成发布在 blueimp github 上不是解决方案。我必须将两者结合使用才能发挥作用。
感谢Loki和Whosebug平台帮我解决了这个问题
screenshot of my post page before/after file upload, index.php (file from the jquery file uploader) files print report, and mysql files table after file uploading