-1

Where am i going wrong in the script below? The back end is PHP. Something seems to be getting uploaded but the PHP script always returns the error below. I'm trying not to use formdata because of older browsers.

Notice: Undefined index: file1 in upload.php on line 2

Notice: Trying to access array offset on value of type null in upload.php on line 2

HTML And Javascript

<!DOCTYPE html>
<html>
<head>
<script>
function _(el){
    return document.getElementById(el);
}
function uploadFile(){
    var file = _("file1").files[0];
    var ajax = new XMLHttpRequest();

    console.log(ajax.response);
    ajax.open("POST", "upload.php");
    ajax.send(file);
}
</script>
</head>
<body>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1"><br>
  <input type="button" value="Upload File" onclick="uploadFile()">
  </form>
</body>
</html>

PHP

<?php
$fileName = $_FILES["file1"]["name"]; // The file name
?>
Norman
  • 6,159
  • 23
  • 88
  • 141

1 Answers1

1

I may be wrong but usually you need to attach a file to a FormData object like this:

let fd = new FormData();
fd.append("nfile",file);
...
ajax.send(fd);

Which is then accessible in PHP using:

$_FILES["nfile"];
gold-dan
  • 44
  • 3
  • I'm actually trying to avoid using formdata – Norman Aug 26 '20 at 06:32
  • @Norman I personally would try to convert the file to base64 then send it basically as a string but if that doesn't fit your requirements I'm not sure what other way there is because just sending the files attached to a JSON array doesn't tend to work – gold-dan Aug 26 '20 at 06:56
  • @Norman why would you want to avoid using formdata? That's the standard way to do this task – ADyson Aug 26 '20 at 07:07
  • @ADyson So it works on older browsers that don't support formdata – Norman Aug 26 '20 at 07:18
  • @Norman you're talking about IE9 and earlier - everything else supports it (see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility). Those browsers have been dead for a long time, they don't run on any supported operating system. Do you **really** need to add lots of extra effort to support them? This won't be the only compromise you have to make to be able to work with those dinosaurs – ADyson Aug 26 '20 at 07:38