jQuery Fileupload and writing filename do MySQL database - php

I'm trying to create a file uploader with jQuery, that uploads a file, renames it with a timestamp and registers it into a DB. Basically it it sends the file with a form to the server where a second script renames it and moves the file to the right directory. This works without any problem. The problem is, that I want to send also the table name where this DB Entry should be made.
So index.php contains the form:
<div id="uploaderMain">
<p>Upload Your Files</p>
<form method="post" enctype="multipart/form-data" action="./upload.php">
<input type="file" name="images" id="images" />
<input type="hidden" name="List" id="List" value="<?php echo $DBTable; ?>" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
The jQuery Code looks like this:
$.ajax({
url: "./uploader/upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
The upload.php looks like this:
<?php
//include db configuration file
include_once('../../db.php');
$List = $_POST['List'];
// get the time stamp for the uploaded file
date_default_timezone_set('EST');
$date = new DateTime();
$date = $date->getTimestamp();
// echo $date;
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
// store the file name and the file ending in 2 variables
$fileEnding = substr($name, -4,4);
$fileName = substr($name, 0, (strlen($name)-4));
$uploadName = $fileName."_".$date.$fileEnding;
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "./uploads/" . $uploadName);
}
}
after that I want to write to the DB. The problem is, that the $_POST['LIST'] statement doesn't provide my DBTable-name.
Can anyone give me a hint?
Cheers
Dan

I think you need to add this to your jQuery code:
formdata.append('List', '[your value]');
Please note: in PHP everything that is a file will go into $_FILES. Everything else will go into $_POST.
If this does not work, make sure you also have the following code:
var formdata = new FormData();
jQuery.each($('input[type="file"]')[0].files, function(i, file) {
formdata.append(i, file);
});

Can you check the source from browser if the List control has any value.

Related

How to upload multiple files using dropzone.js?

My problem is when I drag & drop multiple files that time each image is called a particular ajax. I want to multiple file upload time only one ajax call.
I want to choose a single file and drag & drop it in dropzone and another file drag & drop so as not to replace the file with to first one I need both theme and click on the button that time save in the folder at one time ajax call.
Here is my code
HTML file
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.js"></script>
<div class="row">
<form action="route.php?actionPresubmission=loanPreSubmission" class="form-horizontal dropzone" id="imageform">
</form>
</div>
route.php
$uploadDir = 'upload';
if (!empty($_FILES)) {
$tmpFile = $_FILES['file']['tmp_name'];
$filename = $uploadDir.'/'.time().'-'. $_FILES['file']['name'];
move_uploaded_file($tmpFile,$filename);
}
Thanks
Interpreting the question, I think you want to upload multiple files through one call.
For that, you need to stop autoProcessQueue which is true by default
Script:
Dropzone.options.myDropzone = {
autoProcessQueue: false, //This stops auto processing
acceptedFiles:".png,.jpg", //Change it according to your requirement.
init: function(){
var submit = document.querySelector('#submit');
mydropzone = this;
submit.addEventListener("click", function(){
mydropzone.processQueue();
});
this.on("success", function(file,response){
alert(response);
});
},
};
HTML:
<form action="upload.php" class="dropzone" id="myDropzone"></form>
<div>
<button type="button" class="btn btn-info" id="submit">Upload</button>
</div>
PHP
<?php
$folderName = 'upload/';
if(!empty($_FILES))
{
$file = $_FILES['file']['tmp_name'];
$fileLocation = $folderName . $_FILES['file']['name'];
move_uploaded_file($file,$fileLocation);
} ?>
Hope this helped you :)

posting text file thru jQuery ajax in php and download the response file

Requirement:
I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php
processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.
I have seen many posts but nothing is helping me out.
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
I have tried hundreds of solutions given on the net but none is working.
Here I am providing complete working example:
HTML File:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // 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(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
Download
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
PHP File:
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
Try to upload any file.
Is this useful for you?

how to send formData to php with ajax

I am trying to generate multiple form that will provide a system to upload multiple files. So far code is
<?php
...
foreach($all_cat as $cat)
{
?>
<form method="post" class="uploadform" enctype="multipart/form-data" action="">
<label for="file-upload" class="custom-file-upload">
<i class="cloud-upload"></i> Add Files
</label>
<input id="file-upload" type="file" name="files[]" multiple />
<input type="submit" value ="uplaod" size="60">
</form>
...
<?php
...
jquery
$(".uploadform").on('submit',(function(e)
{
e.preventDefault();
if($('input[type=file]').val()=="")
{
alert("no file is selected");
return false;
}
else
{
$.ajax({
url: "form_process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(result)
{
alert(result);
}
})//ajax
}//else
}));//onsubmit
But it seems that form_process.php file is not getting data form jquery. alert producing long mark-up of table, and somewhere in that it says file name can not be empty.
form_process.php
if(isset($_FILES['files']))
{
foreach($_FILES['files']['tmp_name'] as $key3)
{
$exif = exif_imagetype($key3);
echo "file type is ".$exif."<br/>";
}
How do I access those selected files upload and other data of the form? I have been trying for hours, anybody can help me,please ? Thanks in advance
Try appending them instead of using 'this'.

Getting file out of url with php

So I give my users the possibility to upload a xml file of their iTunes playlist. Once they've uploaded their xml-file, i need to read out that xml file. I tried it first with just an ajax call and a local xml file and it worked fine, but now i need to get acces to the uploaded xml file.
This is my upload form
<form id="formulier" action="playlist.php" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload your playlist</legend>
</br>
<label>
<input type="file" name="bestand">
</label>
</br>
</br>
<input type="submit" value="Generate">
</fieldset>
this is my playlist.php file:
<?php
$path = "playlists/" . ($_FILES['bestand']['name']);
if(move_uploaded_file($_FILES['bestand']['tmp_name'], $path)){
}
header("Location:index.html?url=".$path);
?>
this is my ajax call that i previously used:
var my_fn = function(callback) { // <-- this is callback to be called later
var jax = [];
$.ajax({
url: "",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var content = $(this).next('string').text();
jax.push(content);
});
callback(jax);
}
});
};
How do I get to read out the xml file that is uploaded by the user? I really do not have a clue...

Session Upload Progress, Ajax call and empty $_SESSION

My goal is to, upon clicking the form submit button, to upload the attachments from the form to the server and show a progress bar of that happening and then submitting the form (ie. mailing the message).
upload_form.php:
<form action="email_message.php" method="post" enctype="multipart/form-data" name="fileform" id="fileform">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000"/>
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="uploads"/>
<label for="userfile1">Upload a file:</label>
<input type="file" name="userfile1" id="userfile1" class="userfile"/>
<input id="submit_btn" type="submit" value="Send Message"/>
</form>
In the same page, I run the following code to prevent the form from being executed and sending a request to upload all of the files from the form.
$(document).ready(function(){
$("#fileform").submit(function(e){
e.preventDefault();
var self = this;
var formData = new FormData(document.getElementById("fileform"));
var upload_req = $.ajax({
url: "./upload_multiple_files.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
upload_req.done(function(data){
alert("Uploading complete!");
});
});
});
upload_multiple_files.php:
<?php
session_start();
foreach ($_FILES as $k => $v){
// code to deal with file errors
if (is_uploaded_file($v['tmp_name'])){
// code to rename file
echo "<p>The file was successfully uploaded.</p>";
}else{
echo "<p>The file was not uploaded.</p>";
}
}
?>
All of this works: the files are all uploaded to the server.
The problem I have is integrating PHP Upload Session Progress (http://php.net/manual/en/session.upload-progress.php).
I know I need to use session.upload_progress.name and the $_POST array to get the file upload information but I'm not sure where to place it. I want to create an ajax call with an interval to periodically get the upload progress to be displayed on my form page. However, when I create a new page, the session information is empty. Here is an example of a page I tried:
get_progress.php:
<?php
session_start();
// $key is a combination of session.upload_progress.prefix and session.upload_progress.name
$results = array("content_length" => $_SESSION[$key]['content_length'],
"bytes_processed" => $_SESSION[$key]['bytes_processed']
);
echo json_encode($results);
?>
I checked the session ids from upload_form.php and get_progress.php and they are the same.
Any reason why $_SESSION is empty in get_progress.php? I think I missed something easy but I can't figure it out.
#Perry Your answer is right, session.upload_progress.enabled wasn't enabled in php.ini. Thanks.

Categories