I have tried every proposed solution for last 3 hours and none worked for me. Please keep in mind that I am very new to ajax.
Here is my ajax code:
var formData = new FormData();
formData.append('file', $('#commercialAnimation')[0].files[0]);
$.ajax({
url : 'includes/upload.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
Here is the piece of form (it's last form attribute which is disabled by default):
<label id="uploadAnimation">Upload your file:</label>
<input type="file" id="myfile" disabled>
And here is php class which should retrieve this file:
include 'db_connector.php';
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//file uploaded
}else{
//error while uploading
echo json_encode(array(
'error' => true,
'message' => $message
));
}
When I try to log messages into separate file php code seems to be working but I cannot find the file in any of xampp folders.
Additionally the alert(data); from ajax does not show any value.
You should move the file first to some folder by calling move_uploaded_file:
if ($fileError == UPLOAD_ERR_OK) {
$tmp_name = $_FILES['file']['tmp_name'];
$name = $_FILES['file']['name'];
move_uploaded_file($tmp_name, "$your_uploads_dir/$name");
}
Related
I want to be able to have a user drag and drop a pdf file and have a modal appear for the user to quickly fill out a form about the file. When the user clicks submit, the file and the form data are passed using Ajax to a php file to then have the file upload and the data processed into a DB.
script.js
// On drop calls uploadFile Function and appends to formData object
$("#dropzone").on ('drop', function (e) {
e.preventDefault();
$(this).removeClass('dropzone dragover').addClass('dropzone');
$("#myModal").removeClass("hidden").addClass("visible");
var file = e.originalEvent.dataTransfer.files;
uploadFile(file);
});
var uploadFile = function(files){
formData = new FormData();
formData.append("file", files);
var x;
for (x = 0; x < files.length; x = x + 1){
let file = files[x];
formData.append('files[]', file);
}
};
// On Form submit all data is saved to values and Ajax call to users.php
$("form").on('submit', function(e) {
// e.preventDefault();
var values = $(this).serialize();
$("#myModal").removeClass("visible").addClass("hidden");
url = 'app/forms/users.php'
$.ajax({
type: 'POST',
url: 'app/forms/users.php',
processData: false,
contentType: false,
cache: false,
data: { formData, values },
dataType: 'json',
success: console.log("Done")
});
});
This is where I run into issues. I am able to
console.log(Array.from(formData)) at all points of interaction before the user hits submit. But when the user submits the form it seems the formData vanishes from existence.
users.php
} else if ($_POST['dispatch'] == 'file_upload') {
// Upload File
var_dump($_FILES);
var_dump($_POST);
$errors = [];
$target_dir = 'F:\wamp64\www\blank\dev\uploads/';
$extensions = ['pdf', 'PDF'];
$all_files = count($_FILES['file']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_Name = $_FILES['file']['name'][$i];
$file_Tmp = $_FILES['file']['tmp_name'][$i];
$file_Type = $_FILES['file']['type'][$i];
$file_Size = $_FILES['file']['size'][$i];
$tmp = explode('.', $_FILES['file']['name'][$i]);
$file_ext = strtolower(end($tmp));
$file = $target_dir . date('U')."-".basename($file_Name);
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_Name . ' ' . $file_Type;
}
if ($file_Size > 9000000000000000000) {
$errors[] = 'File size exceeds limit: ' . $file_Name . ' ' . $file_Type;
}
move_uploaded_file($file_Tmp, $file);
if ($errors) print_r($errors);
}
// Process to DB
Currently, the only data I can find is the formData from the form itself. If there is any information that I missed that could be helpful just let me know. Either I need to go about this a different way or I'm just missing something.
Any help is appreciated. Thank you.
I want to upload file to an directory of another outside of my word-press directory.
Here is my HTML
<form>
<div class="form-group upload-btn-wrapper2">
<span id="">Member Passport - Front</span>
<input required="" type="file" dir="rtl" name="member_passport_front_copy_names" id="member_passport_front_copy_names" class="form-control valid" for="UAE citizen" aria-required="true" aria-invalid="false">
</div>
</form>
Here is my AJAX Function.
jQuery(document).ready(function () {
jQuery('body').on('change', '#member_passport_front_copy_names', function (evt) {
var data = new FormData(this.form);
var data = new FormData();
var files = jQuery('#member_passport_front_copy_names')[0].files[0];
data.append('file',files);
jQuery.ajax({
url: '<?php echo site_url(); ?>/wp-admin/admin-ajax.php?action=cms_filesubmit',
type: "POST",
data: data,
mimeType: "multipart/form-data",
contentType: false,
processData: false,
cache: false,
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (response) {
alert("something went wrong");
}
});
});
});
Here is my PHP function to upload file to directory
add_action( 'wp_ajax_cms_filesubmit', 'cms_filesubmit' );
add_action( 'wp_ajax_nopriv_cms_filesubmit', 'cms_filesubmit' );
function cms_filesubmit(){
$target_dir = "http://sajaya.ae/himmah/app/webroot/img/user_upload/";
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"http://sajaya.ae/himmah/app/webroot/img/user_upload/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
}
When ever i change or upload file it give in response Success but file not get uploaded to directory.
move_uploaded_file does not work with HTTP URLs – you need to specify a file system path for the destination.
Either relative to the current working directory of your script, or as a full absolute path from the server file system’s root directory.
I'm not sure how to access the javascript object correctly I think. I'm trying to use ajax to upload a file to php and have the php file handle an unzip to specific directories.
I'm not sure how the unzip would go but I have have the following code so far:
HTML:
<form id="upload_header_modules_form1" enctype="multipart/form-data" method="post" action="" onsubmit="return false">
<label for="themes_edit_file_id1" class="themes_edit_file">Upload .zip file</label>
<input id="themes_edit_file_id1" style="visibility:hidden;" onchange="setfilename1(this.value);" type="file">
<label for="install1" class="normal_button" onclick="uploadZip()">Install</label>
<input id="install1" style="visibility:hidden;" type="submit">
</form>
AJAX:
function uploadZip()
{
formdata = new FormData(document.forms[0]);
if (formdata)
{
$.ajax
(
{
url: "http://localhost/IG_API_2/pages/default_upload/upload_php.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data)
{
$(".modal").css("opacity", "1");$(".modal").css("visibility", "visible");$(".modal_mid").html("<pre>" + data + "</pre>");
alert(data);
}
}
);
}
}
and PHP (I haven't checked the PHP much so don't pay too much attention to this):
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = '../plugins/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
I'm just wanting to
a) get past the PHP error "Undefined Index zip_file in C:\etc"
b) extract the .ZIP file to location "temp/"
Thanks in advance.
Edit We know that the PHP error is an undefined index because the file type is not loading correctly in the $_FILES["zip_file"]. It's not getting the file because of ajax for some reason. I think it's to do with the formdata = new FormData(document.forms[0]); line.
I am building file upload using php and jquery, I made it without a submit button. But everything is working fine but only there is an error it shows me undefined index message.
This is my html code:
<div id='show'></div>
<form action='demo.php' method='POST' enctype='multipart/form-data'>
<input type='file' id='file' name='file'>
</form>
This is my jquery code:
$(document).ready(function(){
$('#file').change(function(){
var name = $('#file').attr('name');
$.ajax({
url: 'demo.php',
type: 'POST',
data: {'file':name},
beforeSend: function(){
$('#show').html('Loading...');
},
success: function(data){
$('#show').html(data);
}
});
return false
});
});
This is my php code:
if(isset($_FILES['file'])){
$file = $_FILES['file'];
// File properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
//Extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('jpg', 'png');
if(in_array($file_ext, $allowed)){
if($file_error === 0){
if($file_size <= 2097152){
$new_file = uniqid('', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $new_file;
if(move_uploaded_file($file_tmp, $file_destination)){
echo $file_destination;
}
}
}
}
}
I don't know what is the error and why it's coming.
You are not sending data to $_FILES, but to $_POST actually.
Note the data parameter in your $.ajax() call: data: {'file':name}
Instead of using the jQuery .ajax function, just have the form "submit
$(document).ready(function(){
$('#file').change(function(){
$('form').submit();
return false
});
});
add following right after
// Disable errors completely
error_reporting(0);
This will help you to remove/ hide all error messages including fatal errors.
Alternatively you can use
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
You can also view PHP Official documents for alternative options.
Viewing your problem in detail seems more identical like you are trying to upload file via Ajax. Please read a sample about this scenario on Simple File Upload Using jQuery.
I'm trying to upload files using php and I am copying and renaming files from other instances that are actually working (uploading pics). But for some reason the form is not passing (POST) any file that is NOT an image :-/
So, in resume, I am getting this (Google) 'request payload' for an image file:
------WebKitFormBoundaryrHOYostaC2KnUDlD
Content-Disposition: form-data; name="uploaded_file[]"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryrHOYostaC2KnUDlD--
But this for txt or pdf files:
------WebKitFormBoundaryc1RJOtSOpYKAZiBz--
Here is the form and script (functions are to avoid the user to click 'Submit', those work good):
echo '
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("uploaded_file");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("uploaded_file");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>';
echo '
<form enctype="multipart/form-data" target="_blank" name="send_file" id="send_file" method="post" action="file_upload.php">
<input type="file" class="hide button" id="uploaded_file" name="uploaded_file" onChange="Handlechange();"/>
<button type="submit" id="btn">Upload!</button>
</form>';
echo '
<div onclick="HandleBrowseClick();" id="fakeBrowse" >Load a file</div>
<input type="text" id="filename" size="50" readonly="true" />
';
So, since it's not passing anything, in my file_upload.php I get the "ERROR: Please browse for a file before clicking the upload button." or "Invalid argument supplied for foreach()" (if I expect an array) error.
I tried using application/x-www-form-urlencoded allowing the same result. Now for those who get mad if there is no question marks: Why the form works fine with images but not so with other kind of files? What am I dong wrong?
Here is the first few lines of file_upload.php (I don't think it's necessary but you never know):
$target = "../files/temp/";
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
if ($error != UPLOAD_ERR_OK) { echo "error"; die;}
$fileName = $target . $_FILES["uploaded_file"]["name"][$key]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$key]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$key]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$key]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$key]; // 0 for false... and 1 for true last $key!!!
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$fileName = strtolower($fileName);
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.";
exit();
}
Finally, some more js:
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Loading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
}).done(function (res) {
document.getElementById("response").innerHTML = res;
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
});
}
}, false);
where changing contentType doesn't make any diference
THANKS!!!
You have to define the MIME types for your files. For example
.pdf application/pdf
.doc application/msword
Okay, my bad. The js file has an image filter. It started working right away after I removed it.