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:我没有找到文件。
您的问题是错误地将数据发送到数据。首先,您正确地形成form_data来提交文件,就好像一个普通的表单被提交,并且编码设置为multipart/form-data。对于正确的,
content-type您设置了processData: false,但由于某种原因,您在 data 中放入了另一个对象,之后在data中获得了“粥” ,而不是发送到服务器。这将是正确的:
查找与您的版本的差异并找出错误。此选项可以正常工作。
这是第一个文件
index.html:第二个文件
script.php: