posting formData to PHP script for file upload - javascript

Not sure why I am unable to send the formData over to my PHP script.
I have used this same code before with success.
Here is the HTML:
<form role="form" id="uploadForm" name="uploadForm" action="index.php" enctype="multipart/form-data" method="post">
<input type="file" id="file" name="file" />
<button type="button" id="uploadSubmit" class="btn btn-sm btn-flat btn-primary uploadSubmit">Upload Proforma</button>
</form>
Here is the JavaScript
$('#uploadSubmit').on('click', function(e){
e.preventDefault();
var formData = new FormData();
formData.append("file", document.getElementById('file').files[0]);
$.ajax({
url: 'api/uploadDoc.php',
method: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: ' + errorThrown);
}
});
return false;
});
Here is the PHP uploadDoc.php script:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
print_r($_POST);
?>
I just added the headers in the PHP script, as found here:
FormData not posting data to php backend script
Using print_r($_POST), I am only getting a blank array in the console that looks like the following:
Array
(
)
Not sure what I am doing wrong.
Why is the post showing a blank array and the file information or formData?
How do I correct this issue so that the PHP script can retrieve the file that I am uploading?

You need to get the files using the variable $_FILES instead of $_POST

You can make sure the uploaded file by using is_uploaded_file. But if you want to retrieve the file contents, simply you can use readfile as following:
if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
die("Possible file upload attack: filename '". $_FILES['file']['tmp_name'] . "'.");
}
echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['file']['tmp_name']);

I found my answer here:
jQuery AJAX file upload PHP
I updated my onClick event to read as follows:
$('#uploadProformaSubmit').on('click', function(e){
e.preventDefault();
var file_data = $('#file').prop('files')[0]; // <-- added this
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'api/uploadDoc.php',
method: "POST",
type: "post", // <-- added this
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: ' + errorThrown);
}
});
return false;
});
Over in the PHP script, I could do the following:
<?php
if(isset($_FILES['file'])){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
echo "this is the file " . $file;
?>
And now the file is posting.
Maybe because the site is using an older version of JQuery (1.8.2.min.js), though I cannot be certain.

Related

Uncaught TypeError: Illegal invocation when trying to upload file via ajax? [duplicate]

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

Ajax file upload not being store in the directory

I'm in the process of building a function in uploading a file(CSV) using AJAX. This is just a rough code since that I'm working and currently following a tutorial. I'm using XAMPP for server side languages
After executing i'm getting an alert that displays (obect FormData) inside and aside from that, the uploads directory is empty after submitting the file. Project currently has three items. (Uploads Folder, index.php and upload.php)
HTML
<form method="post" enctype="multipart/form-data">
<input id="file-uploading" type="file" name="fileUploading" />
<button id="upload" value="upload">Upload</button>
</form>
JAVASCRIPT
$('#upload').on('click', function() {
var file_data = $('#file-uploading').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
console.log('success');
}
});
});
PHP
<!doctype html>
<html>
<body>
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error' . $_FILES['file']['error'] . '<br/>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
</body>
</html>
I test successful.I think "uploads" permissions is not right.You should do:
sudo chown -R www-data:www-data uploads
I think you are missing out on enctype attribute on form.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
<form method="post" enctype="multipart/form-data">
// your content
</form>
Hope this helps..

How do I upload a (.OBJ) Blob file to the server using PHP and jQuery?

I have been trying to upload a file from my webpage to a folder on the server using jQuery and PHP.
Here is my JavaScript code for generating the file to send and then using a POST request to send the file to my PHP script so that it can then handle the file and save it to a particular folder.
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('Character', characterBlob);
//Communicate with the server
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
Here is my PHP script to handle the sent file and save it in a specified folder.
<?php
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/Applications/AMPPS/www/webGL/upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
?>
When I try to send the file from my webpage nothing appears in the 'Upload' folder that I am trying to save the file to.
Could someone please tell me why a file is not saved in the 'Upload' folder? I am eventually looking to open this file in a Maya application on the server and run some Python code. Would I even need to save the file on the server before opening it in Maya? Or could I open Maya with the file straight away?
Try use my code and tell me if it works. This should work if you adapt it to your filenames and input, and other elements ids, it's tested by me:
$('#upload').on('click', function(e) {
$('#message').fadeOut();
e.preventDefault();
if ($('#file')[0].files.length == 0) {
alert('Choose a file!');
} else {
var file_data = $('#file').prop('files')[0]; //file object details
var form_data = new FormData($('#form')[0]);
form_data.append('file', file_data);
var unique_identifier = $('#unique_identifier').val();
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response) {
$('#message').html(php_script_response).fadeIn();
//alert(php_script_response); // display response from the PHP script, if any
}
});
}
});
<form id='form' action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='unique_identifier' id='unique_identifier' placeholder='unique identfier' value="<?php echo rand(1000000, 9999999); ?>">
<input type='file' name='file' id='file' />
<a id='upload'>Upload</a>
</form>
And the PHP script I made:
$unique_identifier = (isset($_POST['unique_identifier']))?trim($_POST['unique_identifier']):'';
$upload_directory = 'upload/' . $unique_identifier . '/';
if (!file_exists($upload_directory)) {
mkdir ($upload_directory, 0777);
}
$original_filename = basename($_FILES['file']['name']);
$destination = $upload_directory . $original_filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination)
Also, I recomend you to do some PHP validation.
It seems you are not appending the file to uploaded to the form data, May be you need something like this.
var elem = $(this).val() // lets say this is the element where you uploaded the photo
var formData = new FormData();
formData.append('file', elem[0].files[0]);
$.ajax({
url: "ExecuteMaya.php",
type: "POST",
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(result){
// your code executed successfully
}

retrieve formdata .append method in php

I upload text/plain file and pass it to php do something via jquery ajax. However, jquery ajax return jquery-2.2.3.js:8998 Uncaught TypeError: Illegal invocation
Check jquery code which look like below
<input type="file" id="file">
<input type="submit" value="submit" id="btnUpload">
<script>
$(document).ready(function(){
$('#btnUpload').click(function(){
var ajaxData = new FormData();
ajaxData.append('action', 'scan_email');
ajaxData.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'ajax.php',
data: ajaxData,
method: 'POST',
// beforeSend: function(){
// // alert('uploading..');
// },
success: function(data){
alert(data);
},
error: function(err){
alert('error');
}
});
});
});
</script>
ajax.php
<?php
echo $_POST['action'];
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'scan_email':
scan_email();
break;
}
}
function scan_email(){
if ($_FILES["file"]["error"] > 0)
echo "Error: " . $_FILES["file"]["error"] . "<br />";
else if ($_FILES["file"]["type"] !== "text/plain")
echo "File must be a .txt";
else{
//do something
echo 'success';
// $file_handle = fopen($_FILES["file"]["name"], "rb");
}
exit;
}
?>
ADD:
processData: false, // tell jQuery not to process the data
ProcessData flag set to false, otherwise, jQuery will try to convert your FormData into a string
contentType: false, // tell jQuery not to set contentType
ContentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it.

jQuery AJAX file upload PHP

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

Categories

Resources