-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
?>
2
  • 1
    "Something seems to be getting uploaded" sounds pretty broad. What have you tried to debug what exactly is happening? Commented Aug 26, 2020 at 6:23
  • I've posted the error i get in PHP Commented Aug 26, 2020 at 6:39

1 Answer 1

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"];
Sign up to request clarification or add additional context in comments.

5 Comments

I'm actually trying to avoid using formdata
@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
@Norman why would you want to avoid using formdata? That's the standard way to do this task
@ADyson So it works on older browsers that don't support formdata
@Norman you're talking about IE9 and earlier - everything else supports it (see developer.mozilla.org/en-US/docs/Web/API/…). 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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.