I am using the code below to upload files to WordPress from a frontend form and get their metadata, which is used to populate fields etc:
var formData = new FormData();
formData.append("action", "upload-attachment");
var fileInputElement = document.getElementById("entryfile");
formData.append("async-upload", fileInputElement.files[0]);
formData.append("name", fileInputElement.files[0].name);
formData.append("_wpnonce", upload_nonce);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
}
}
xhr.open("POST","wp-admin/async-upload.php",true);
xhr.send(formData);
However, this code only works for logged-in users. If the visitor is not logged in, the console logs a redirect that looks like:
wp-login.php?redirect_to=http:// ...
Why doesn’t this work? Is there a workaround for this?
** UPDATE: **
I ended up using formData to upload the file. However, I cannot seem to be able to handle it after that point. Here is the code I am using in my php ajax handler:
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
echo json_encode("upload error : " . $_FILES[$file]['error']);
exit;
}
$attach_id = media_handle_upload( $file, 0 );
}
}
I always get an error. Either that the file is empty (though the $_FILES array contains the file data), or just an empty error… Help please….