I Have got the Following Problem:
I'm trying to Upload a File via a Form over Ajax
Here is the HTML File:
<html>
<header>
<link rel="stylesheet" href="useme.css"/>
<script src="jq.js"></script>
<script src="actions.js"></script>
</header>
<body>
<form enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" id="file" name="file"/>
<input type="button" value="Click" id="submitBtn"/>
</form>
<span class="status">no status</span>
</body>
The JavaScript File:
/**
* Created by Kenny on 12.04.2015.
*/
$(document).ready(function(){
$("#submitBtn").click(function(){
var filename = $("#file").serialize();
$.ajax({
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
url: "upload.php",
enctype: 'multipart/form-data',
data : {
file: filename
},
type : "POST",
success: function(data){
if(data != "fail")
$(".status").html("Upload is availible at: " + data);
else
$(".status").html("Upload failed.");
}
});
});
});
And last but not lately the PHP File that does the Magic (Not really atm)
<?php
/**
* Created by PhpStorm.
* User: Kenny
* Date: 12.04.2015
* Time: 23:55
*/
$uploaddir = '/many/upload/' . uniqid() . '/';
if(!file_exists($uploaddir)){
mkdir($uploaddir, 0777, true);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://use.hints.me/" . $uploaddir;
file_put_contents($uploaddir . "/index.php", "<?php Header('Location: " . basename($_FILES['userfile']['name']) . "'); ?>");
} else {
echo "fail";
}
?>
My Problem here is that I only get empty $_FILES in the PHP-File, the PHP File somehow works fine when i use a Standard POST form, but with Ajax it doesnt work at all.
Excuse my messy Code, it's just a Proof of Concept to a friend of mine and not at all used for Providing a serious File Upload site. I just want to get this working.
Things i checked here before:
check the php.ini File if the File Upload is enabled
added enctype="multipart/form-data" to the Form
added the MAX_FILE_SIZE tag to the Form
checked StackOverFlow all over
Related
I was trying to upload file on server using php with jQuery's ajax() function. Below is the code which I was trying. Things worked fine when I wrote PHP code on same page without jQuery, so there is no doubt that file upload is working.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$("form").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append("files", $("#fileinput").prop("files"));
$.ajax({
url: "imgupload_.php",
type:"POST",
processData: false,
contentType: false,
data: fd,
success: function(result){
alert(result);
}
});
});
});
</script>
<form method="POST" action="#" enctype="multipart/form-data">
<input type='file' name='files' id="fileinput"/>
<input type='submit' value='Submit' name='submit'/>
</form>
imgupload_.php
if(isset($_POST["submit"])) {
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["files"]["name"]);
if (move_uploaded_file($_FILES["files"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["files"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
If you want any other info please comment below.
You're checking if(isset($_POST["submit"])) but this is not set.
Instead of just this:
var fd = new FormData();
Use this to pull in any non-file input values (such as your submit button.)
var fd = new FormData(this);
Below code works well when I am executing PHP in same page but it does not work when I execute script_add_business.php using jquery. Particularly HTML html file upload does not send any value but when I tried getting other fields values like textbox, I am successfully getting them.
MY HTML:
<form method="post" enctype="multipart/form-data" id="addBusinessForm" class="form-horizontal addBusinessForm" action="">
<input type="file" name="logo" class="form-control">
<button type="submit" id="addBusiness" class="btn btn-custom">Upload Logo</button>
</form>
JQUERY within HTML page:
<script type="text/javascript">
//Add Invoice Form
$('#addBusiness').click(function() {
$.post("script_add_business.php", $(".addBusinessForm").serialize(), function(response) {
$('#success').html(response);
$('#success').show();
if (response == 'OK') {
$('#addBusinessForm')[0].reset();
$('#success').text('Your Business has been successfully submitted. People can see it live once we approve it.');
}
});
return false;
});
</script>
script_add_business.php CODE:
if(!empty($_FILES['logo']['name']))
{
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$imgname = basename($_FILES["logo"]["name"]);
$target_file = $target_dir .$imgname;
echo "File path is:". $target_file; exit;
}
I really appreciate help.
Please refer this url's, these may help you
https://stackoverflow.com/a/8758614/1072492
http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
You can't upload file with jQuery $.post method.
Try like this .
<form method="post" enctype="multipart/form-data" id="addBusinessForm" class="form-horizontal addBusinessForm" action="">
<input type="file" name="logo" class="form-control">
<button type="submit" id="addBusiness" class="btn btn-custom">Upload Logo</button>
</form>
$('#addBusiness').click(function() {
var formData=new FormData();
formData.append("image",$('[name="logo"]')[0].files[0]);
$.ajax({
url: 'script_add_business.php',
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(response){
// Do stuffffff
}
});
return false;
});
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?
Here is what I have tried so far and it isn't working. The HTML file contains:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Generator | Upload Driver Specification Sheet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type='text/javascript'>
function submit_form() {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'last_file_action.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
$('#results').html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
</head>
<body class="gray-bg3_full">
<form class="m-t" role="form" id='data' method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<div class="form-group">
<p id='new_project_text'>Please include your Product spec sheet: </p>
<input class="btn btn-primary-save btn-block" type="file" name="userfile" /> <i class="fa fa-upload"></i> <br/>
</div>
<button type= 'button' id="submit_driver" class="btn btn-warning block full-width m-b m-t" onclick='submit_form()'>Submit</button>
</form>
<div id='results'></div>
</body>
</html>
And the PHP file i.e. 'last_file_action.php' contains this:-
<?php
if ($_FILES['userfile']['error'] > 0)
{
switch ($_FILES['userfile']['error'])
{
case 1:
echo "File exceeded upload_max_filesize";
break;
case 2:
echo "File exceeded max_file_size";
break;
case 3:
echo "File only partially uploaded";
break;
case 4:
echo "Please choose a file to upload";
break;
case 6:
echo "Cannot upload file: No temp directory specified";
break;
case 7:
echo "Upload failed: Cannot write to disk";
break;
}
exit;
}
$upfile = 'productinformation/';
if (is_uploaded_file($_FILES['userfile']['tmp_name']))
{
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile))
{
echo "Problem: Could not move file to destination directory";
exit;
}
}
else
{
echo "Problem: Possible file upload attack. Filename: ";
echo $_FILES['userfile']['name'];
exit;
}
// remove possible HTML and PHP tags from the file's contents
$contents = file_get_contents($upfile);
$contents = strip_tags($contents);
file_put_contents($_FILES['userfile']['name'], $contents);
// show what was uploaded
When I click the submit button I get this error "Problem: Possible file upload attack. Filename:". This is the error I've myself set in PHP file. It shows this error even when I don't select the file to upload. I want it to show Error "Please choose a file to upload" if I don't select a file to upload.
var formData = new FormData();
formData.append("userfile", $(":file")[0].files[0]);
Here is how I did it.
var formData = new FormData();
formData.append("userfile", $(":file")[0].files[0]);
The above code is right as long as you have one file and no other input fields. In case you have more input field and multiple file upload in a single form. One should consider target elements by their IDs instead of type $(":file").
Here is how we can get other files:-
var formData = new FormData();
formData.append("first_file", $("#1st_file_id")[0].files[0]);
formData.append("2nd_file", $("#2nd_file_id")[0].files[0]);
formData.append("3rd_file", $("#3rd_file_id")[0].files[0]);
Here is how we can get data from input fields of form by targeting their IDs.
formData.append("input_field", $("#input_field_id").val());
In PHP nothing needs to be changed. If we want to get the value of input field we can do it by:-
$var = $_POST['input_field'];
And if its a file, we can capture it by this and do the rest of the work as done in the question.
$_FILES['userfile'] or $_FILE['2nd_file']
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.