我有这个 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 上传文件
- 将文件按原样存储到具有相同名称的"/uploads/">
- 将文件名与消息一起放在数据库中
注意:表单已经运行良好(提供的代码只是一个最小版本(我只需要处理文件。
您尚未在 ajax 请求中包含 mimetypes。 mimeTypes: "multipart/form-data"
ajax 中添加这个
尝试使用表单数据发送输入值
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);
},
});
}