Ajax file upload not being store in the directory - javascript

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..

Related

posting formData to PHP script for file upload

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.

Ajax POST format with PHP

I have a form, inside which I want to have a "virtual form", which handles file attachments. I have a File-input and a button to send the file.
The problem is that my PHP backed gets only POST and that with structure:
"file"; filename="xxx.jpg"
Content-type: image/jpeg
.
.
.
where the dots represent the binary data from the file.
From what I have read it should be $_FILES and $_POST variables but I don't get them.
Here are the relevant codelines in HTML and in Javascript:
<input type="file" id="file-to-append" name="file-attachment">
<input type="button" onClick="append_file()" value="Add file">
function append_file() {
var formData = new FormData();
console.log(jQuery('#file-to-append'));
formData.append('file', jQuery(":file")[0].files[0]);
jQuery.ajax({
url : 'file_upload.php',
type : 'POST',
data : formData,
processData: false,
success : function(data) {
console.log(data);
alert("Added");
}
});
}
Could somebody spot or know where the problem lies?
The data is passing properly so there is no problem with your Ajax call.
You get the file object in PHP using the super global $_FILES.
In your case, you would use it like:
$file = $_FILES['file'];
echo $file['name'];
echo $file['tmp_name'];
.
.
.
To take a look at the $_FILES array you could:
echo "<pre>";
print_r($_FILES);
echo "</pre>";
Things are getting stranger and stranger. I got it working, but only on IE 11 by setting contentType: 'multipart/form-data' With Chrome it doesn't work at all with that setting.
I have tried with contentType: false, but it doesn't work on either platform though it should be the right thing(TM) to do :/.
I have also added enctype-setting in the outer form, but I wonder how it could help, because I am not submitting (whole form) but only adding things "inside" the main form (that I handle myself). Apparently it didn't help either.
This shouldn't be a problem but for some reason I am stuck with this ajax implementation, though I have used file upload since long time ago (two figure number)...
hank
Use right encrypte in your form
<form id="data" enctype="multipart/form-data" method="post" >
<input type="submit" value="Add file">
</form>
use ajax submit
$("form#data").submit(function()
{var formData = new FormData($(this)[0]);
$.ajax({
url: "filename.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
var jsonData = $.parseJSON(data);
var errFlag =jsonData.errorFlag;
var errMsg =jsonData.errorMessage;
if(errFlag == 1)
{
//successmessage;
}
else
{
//errormessage;
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});

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
}

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

PHP upload file to Ajax using onchange

function chkFile(file1) {
var file = file1.files[0];
var formData = new FormData();
formData.append('formData', file);
$.ajax({
type: "POST",
url: "chkFileType.php",
contentType: false,
processData: false,
data: formData,
success: function (data) {
alert(data);
}
});
}
<form action="" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Upload Files
<input type="file" name="uploadFile" id="uploadFile" onChange="chkFile(this)"/>
<input type="submit" name="submitbutt" value="Checkout">
chkFileType.php
<?php
print_r($_FILE)
?>
I want to create a form that when the user uploads a file, it will do a check on the uploaded file before submitting the whole form. I use onChange when a file is uploaded and then pass the formData value to Ajax to call my chkFileType.php to do the checks and alert back the response.
The function is running without any errors, but no response from alert(data);
I know I am doing something wrong, but have no idea which direction to go from. Am I doing the right way?
Everything looks fine. You have done in right way. But to get any response from an ajax call, you have to print the required stuff in chkFileType.php.
Like,
if($ext =="jpg" || $ext == "png"){
echo "Image"; // data in alert will alert as Image
} else if(check for txt file){
echo "Text File"; // data in alert will alert as Text File
} else if(chck for pdf) {
echo "Pdf";// data in alert will alert as Pdf
}
EDIT
change this
var formData = new FormData( $("#formID")[0] );
Hope you understand what i meant to say.
I think the problem is in that you have written "type" instead of "method", "POST" is a method not a type.

Categories

Resources