JavaScript
$(document).ready(function () {
'use strict';
$('#u_button').click(function () {
var file_data = $('#u_jfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "http://example.ru/script.php",
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: {
class: $('#u_class').val(),
subject: $('#subject').val()
}, form_data,
type: 'post',
success: function(data) {
console.log(data.message);
}
});
});
});
PHP
<?php
if ( ( !empty( $_FILES[ 'file' ] ) ) && ( $_FILES[ 'file' ][ 'error' ] == 0 ) ) {
$filename = basename( $_FILES[ 'file' ][ 'name' ] );
$ext = substr( $filename, strrpos( $filename, '.' ) + 1 );
if ( ( $ext == "txt" ) && ( $_FILES[ "uploaded_file" ][ "size" ] < 350000000 ) ) {
$newname = "../one/two/" . $_POST[ 'class' ] . "/" . $_POST[ 'subject' ] . ".txt";
if ( ( move_uploaded_file( $_FILES[ 'file' ][ 'tmp_name' ], $newname ) ) ) {
$date = date( 'd.m.Y_H:i:s' );
$newfile = "../one/two/{$_POST['class']}/{$_POST['subject']}/{$date}.bak.txt";
if ( !copy( $newname, $newfile ) ) {
echo json_encode( array( "status" => "FALSE", "message" => "Ошибка загрузки" ) );
die();
} else {
echo json_encode( array( "status" => "TRUE", "message" => "Загружено" ) );
die();
}
} else {
echo json_encode( array( "status" => "FALSE", "message" => "Ошибка загрузки" ) );
die();
}
} else {
echo json_encode( array( "status" => "FALSE", "message" => "cerr: ext or size" ) );
die();
}
} else {
echo json_encode( array( "status" => "FALSE", "message" => "cerr: i not found file" ) );
die();
}
?>
HTML
<label class="file_upload" id="u_file">
<span>Выбрать файл</span>
<input type="file" id="u_jfile" name="n_jfile" accept=".txt">
</label>
Сталкиваюсь с ошибкой:
cerr: i not found file.
Ваша проблема в неправильной отправке данных в data. Вначале Вы правильно формируете form_data, что отправить файл как еcли бы была отправлена обыкновенная форма с encoding установленным в multipart/form-data.
Для правильного content-type Вы ставите processData: false, но в data зачем-то ставите еще один объект, после чего в data получается "каша", которая не отправляется на сервер.
Правильно будет так:
$('#u_button').click(function () {
var file_data = $('#u_jfile').prop('files')[0];
var form_data = new FormData;
form_data.append('file', file_data);
form_data.append('class', $('#u_class').val());
form_data.append('subject', $('#subject').val());
$.ajax({
url: "http://example.ru/script.php",
dataType: 'json',
data: form_data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log(data.message);
}
});
});
var data = new FormData();
data.append("email", "Email пользователя");
data.append("message", "Какое-то сообщение");
// прикрепляем файлы
$.each($("#files")[0].files, function(i, file) {
data.append("file[]", file);
});
// строим AJAX
$.ajax({
url: window.location.href,
type: "POST",
data: data,
processData: false,
contentType: false,
success: function(data){
console.log(data);
},
error: function( jqXHR, textStatus, errorThrown ){
console.log('ОШИБКА: ' + textStatus );
}
});
Найди отличия от своего варианта и найдеш ошыбку. Этот вариант работает верно.
Это первый файл index.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>
</title>
</head>
<body>
<label class="file_upload" id="u_file">
<span>Выбрать файл</span>
<input type="file" id="u_jfile" name="n_jfile" accept=".txt">\
<button type="submit" id="u_button">submit</button>
</label>
<script type="text/javascript">
$(document).ready(function () {
'use strict';
$('#u_button').click(function () {
var file_data = $('#u_jfile').prop('files')[0];
var form_data = new FormData;
form_data.append('file', file_data);
$.ajax({
url: "script.php",
data: form_data,
dataType: 'json',
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log(data.message);
}
});
});
});
</script>
</body>
</html>
Второй файл script.php:
<?php
if ( !empty($_FILES['file']) && $_FILES[ 'file' ]['error'] == 0 ) {
$filename = basename( $_FILES[ 'file' ][ 'name' ] );
$ext = substr( $filename, strrpos( $filename, '.' ) + 1 );
if ( ( $ext == "txt" ) && ( $_FILES[ "uploaded_file" ][ "size" ] < 350000000 ) ) {
$newname = "test.txt";
if ( ( move_uploaded_file( $_FILES[ 'file' ][ 'tmp_name' ], $newname ) ) ) {
$newfile = "test1.txt";
if ( !copy( $newname, $newfile ) ) {
echo json_encode( array( "status" => "FALSE", "message" => "Ошибка загрузки1" ) );
die();
} else {
echo json_encode( array( "status" => "TRUE", "message" => "Загружено2" ) );
die();
}
} else {
echo json_encode( array( "status" => "FALSE", "message" => "Ошибка загрузки3" ) );
die();
}
} else {
echo json_encode( array( "status" => "FALSE", "message" => "cerr: ext or size" ) );
die();
}
} else {
echo json_encode( array( "status" => "FALSE", "message" => "cerr:qwedf i not found file" ) );
die();
}
?>
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости