<div class="grid--cell fl1 lh-lg">
<div class="grid--cell fl1 lh-lg">
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, <a href="/help/reopen-questions">visit the help center</a>.
</div>
</div>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2013-04-17 03:13:11Z" class="relativetime">7 years ago</span>.</div>
</div>
</aside>
I want to be able to upload files using AJAX.
I've tried using (JavaScript):
$("input[type='file']").change(function(){
var file = document.getElementById("uploadelement").files[0];
$.ajax({
url: "upload.php",
type: "POST",
beforeSend: function(xhr){
xhr.setRequestHeader("X_FILENAME", file.name);
},
success: function(data){
console.log(data);
}
});
});
With (PHP):
<?php
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
?>
However, i'm having the issue, that the files content isn't show up. I'm not sure whats going wrong. I have found this code on a tutorial so I figured it should be working.
The file is uploaded to the folder but there is no content.
</div>
I don't know with the jQuery $.ajax()
call, but this can be achieved by using an XMLHttpRequest
, like so:
var file = document.getElementById("uploadelement").files[0];
var form_data = new FormData();
form_data.append("userfile", file);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "upload.php");
xmlhttp.send(form_data);
Then in your PHP upload handler (upload.php in here):
move_uploaded_file($_FILES["userfile"]["tmp_name"], "path/to/uploads/" . $_FILES["userfile"]["name"]);
And then the file should already be saved to the desired directory.