attachments – Nothing in the uploads folder after wp_insert_attachment

I'm trying to add a text file as an attachment

I first activated the mime type

add_filter (& # 39; upload_mimes & # 39 ;, & # 39; my_myme_types & # 39 ;, 1, 1);
function my_myme_types ($ mime_types) {
$ mime_types['txt'] = & # 39; text / plain & # 39 ;;
return $ mime_types;
}

After sending the front-posting form, I send the text block to the server via ajax so that I can add it to a text file, and then insert it as an attachment .

function rt_new_template () {
global $ post;
$ user_id = absint ($ _ POST["uid"])
$ post_title = sanitize_text_field ($ _ POST["post_title"])
$ post_object = get_page_by_title ($ post_title, OBJECT, & # 39;)
$ post_id = $ post_object-> ID;
$ msg_array = $ _POST["msgArray"];
$ ext = ".txt";
$ file = $ user_id. $ post_title. $ ext;
// $ date = date ("J / m / j");
file_put_contents ($ file, $ msg_array);
$ wp_upload_dir = wp_upload_dir ();
$ attachment = array (
& # 39; guid & # 39; => $ wp_upload_dir['url'] . & # 39; / & # 39 ;. base name ($ file),
& # 39; post_mime_type & # 39; => & # 39; text / plain & # 39;
& # 39; post_title & # 39; => $ user_id. $ post_title,
& # 39; post_content & # 39; => $ user_id. $ post_title,
& # 39; post_status & # 39; => & # 39; inherit & # 39;
)

$ mid = wp_insert_attachment ($ attachment, $ file, $ post_id);
if (! is_wp_error ($ mid)) {
wp_update_attachment_metadata ($ mid, wp_generate_attachment_metadata ($ mid, $ file));
}
die();
}

Once finished, I can see the newly created multimedia file in the Administrative Media section. It only shows a document icon in the preview section.

The URL in the preview of the file is

http: //localhost/wp/wp-content/uploads/224331554033108974.txt

But going to this address gives me a 404 and there is no text file in the uploads folder.