将 jquery FileUploader 连接到我的 MySQL 数据库


Connect Jquery FileUploader To My MySQL Database

当文件上传以发布到我网站配置文件上的客户端时,我正在尝试将我网站后期格式上的 blueimp jquery 文件上传器连接到 mySQL 数据库。我遵循了几个堆栈流线程上的说明,并使用了blueimp的github sql数据库集成说明。

我获取要上传到 GoDaddy 服务器上指定文件路径的文件,文件显示在列表中,但文件属性不存储在数据库文件表中。如果我提交帖子,除了随帖子上传的文件的详细信息外,所有内容都存储在我的数据库中。

我当前的代码:(索引.php来自文件上传器的文件,位于默认服务器/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();

(上传处理程序.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'], '/'));
    }

(主.js来自上传器的文件 正如我在线程中看到的那样.php我将网址从服务器/php 更改为服务器/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');
});

(上传者所在的帖子页面的后端)

...
<!-- 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">&nbsp;</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">&nbsp;</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">&nbsp;</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>&nbsp;</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>&nbsp;</td>
						<td>&nbsp;</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">&nbsp;</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>

(前端连接到我的帖子页面)

<?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);
?>

(我第一次尝试从文件上传器获取文件的后控制器文件)

<?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']);
?>

索引的屏幕截图.php用于我尝试按照说明连接到数据库的上传者MySQL Post & Files 表的屏幕截图,按照说明创建的字段

我能够从 loki 发布的另一个线程中遇到的响应中获取要在 blueimp jQuery 文件上传器和 mySQL 数据库之间建立的连接。如果您不知道自己在做什么,那么使用不太有用的集成发布在 blueimp github 上并不是解决方案。我必须将两者结合使用才能正常工作。

我要感谢Loki和stackoverflow平台帮助我解决这个问题。

文件上传之前/之后我的帖子页面的屏幕截图,索引.php(来自jQuery文件上传器的文件)文件打印报告和文件上传后的MySQL文件表