jQuery文件上传并将Filename放入数据库

时间:2018-04-06 11:48:39

标签: javascript jquery ajax file-upload jquery-file-upload

我有这个AJAX消息表单:

HTML:

<form class="" id="message-form" action="message-send.php" method="POST">
  <div class="form-group">
    <textarea name="message" id="message-field" rows="3" class="form-control message-field"></textarea>
  </div>
  <div class="form-group">
    <input type="file" id="file" name="file">
  </div>
  <div class="form-group text-right">
    <input type="submit" id="submit" class="btn btn-success btn-sm msg-send" value="Envoyer" disabled>
  </div>
</form>

JavaScript的:

var message_form = $('#message-form');
message_form.submit(function (e) {
    e.preventDefault();
    $('#submit').attr('disabled', true).val('Sending...');

    $.ajax({
        type: message_form.attr('method'),
        url: message_form.attr('action'),
        data: message_form.serialize(),
        success: function (data) {
            console.log('Submission was successful.');
            console.log(data);
            $('#message-field').val('');
            $('#submit').val('Send');
        },
        error: function (data) {
            console.log('An error occurred.');
            console.log(data);
        },
    });
});

PHP:

require 'config.php';

$message = $_POST['message'];

$query = 'INSERT INTO messages (time, from, to, message, file) VALUES (?, ?, ?, ?, ?)';
if (!($stmt = $mysqli->prepare($query))) {
    echo $mysqli->error;
}
$stmt->bind_param('iiiss', $time, $from, $to, $message, $file);
$stmt->execute();
$stmt->close();
$mysqli->close();

现在我需要:

  • 使用AJAX上传文件
  • 将文件按原样存储到&#34; / uploads /&#34;同名
  • 将文件名放在数据库中并显示消息

注意:表单已经运行良好(提供的代码只是一个最小版本)我只需要处理文件。

1 个答案:

答案 0 :(得分:0)

您的ajax请求中未包含mimetypes。  mimeTypes: "multipart/form-data"在ajax

中添加此内容

尝试使用formdata发送输入值

var message_form = $('#message-form');
message_form.submit(function (e) {
    e.preventDefault();
    $('#submit').attr('disabled', true).val('Sending...');
       var message_form = $('#message-form');
       var file = $('#file');
       var formdata = new FormData();
       formdata.append('file', file.files[0]);
       formdata.append('message', $('#message-field').val());
       $.ajax({
            type: message_form.attr('method'),
            url: message_form.attr('action'),
            mimeTypes: "multipart/form-data,
            data: formdata,
            async: true,
            contentType: false,
            processData: false,
            beforeSend: function(){

            },
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
                $('#message-field').val('');
                $('#submit').val('Send');
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    }