multipart fileupload with formdata - javascript

I'm trying to upload a file with formdata. the file alone works, but I need to upload some userdata. I tried to append formdata, but when i "print_r" the array($_FILES) in the php file called by ajax it doesn't appear there.
If someone has a solution for the issue, or a better way to tackle a fileupload with userdata, please let me know!
Below you can find the code used:
php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" enctype="multipart/form-data" id="myform">
<input type="text" id="test" value="sample">
<div >
<img src="" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
//console.log("piemel");
console.log(document.getElementById('test').value);
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('test', document.getElementById('test').value);
fd.append('file',files);
console.log(fd);
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</html>
Ajax file:
<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
}else{
echo 0;
}

I have an example working demo code for this (I was also facing this issue and created this script)
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="uploadForm" action="upload.php" method="post">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type='text' name="my_name" value="harish">
<input type="submit" value="Submit" class="btnSubmit" />
</form>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
});
</script>
upload.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES["userImage"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userImage"]["name"]);
$file_extension = end($temporary);
$file_type = $_FILES["userImage"]["type"];
if ((($file_type == "image/png") || ($file_type == "image/jpg") || ($file_type == "image/jpeg")
) /*&& ($_FILES["file"]["size"] < 100000)*/ //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["userImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["userImage"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("uploads/" . $_FILES["userImage"]["name"] . '-'.time()))
{
echo $_FILES["userImage"]["name"] . time() ." <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['userImage']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/".$_FILES['userImage']['name'].'-'.time(); // Target path where file is to be stored
//check the writable permissions
/*if (is_writeable('uploads/' . $_FILES['userImage']['name'])) {
die("Cannot write to destination file");
}*/
if(move_uploaded_file($sourcePath,$targetPath)) {
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["userImage"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["userImage"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["userImage"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["userImage"]["tmp_name"] . "<br>";
} else {
echo "<pre>"; print_r($_FILES['file']['error']); echo "</pre>";
}
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
*Create a folder upload on the same level or change the upload path and make sure to give it writable permissions.
This script is working for both data and files, For post data you need to use $_POST['post_input'].
Give this script a go and hope it will help you.

$_FILES is for files not for data as you are sending data by post use $_POST

Hm. are you trying to upload large files? Because when i was messing around with $_FILES, uploading files bigger than 20mb was unsuccessful until i put the maximum file for upload in my IIS to maximum i could of transfer large files. Only thing i could upload without messing with IIS was normal images.
Your code doesnt seem wrong as it has to put the temp file into the location you provided so What are you exactly trying to upload? The folder "upload" that you are using in your code, does it exist? it wont move any files if the folder doesnt exist either

Related

When trying to insert the path of an uploaded file to MySQL a duplicate is created

I am trying to insert the paths to one user uploaded image($picpath), one user input($uname) and to an html file with variable content($profilepath) into a MySQL table like so:
<?php
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
$temp = explode(".", $_FILES["fileToUpload"]["name"]);
$imageFileType = end($temp);
$random = uniqid();
$imgname = "img$random.$imageFileType";
$picpath = "uploads/$imgname";
if ($uploadOk == 0) {
echo "sorry not able to upload file";
}
else {
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/ . $imgname)) {
echo "the file " .$imgname. " has been uploaded!";
}
else {
echo "sorry there was an error.";
}
}
$uname = $_POST['uname'];
$filecount = count(glob("usertest/*.html"));
$filename = "user" .($filecount+1).".html";
$profilepath = "usertest/$filename";
$myfile = fopen("usertest/$filename", "w") or die("unable to create file");
$html = "<html><body><h1>this is" .$uname."'s profile</h1></body></html>";
fwrite($myfile, $html);
fclose($myfile);
$servername = "127.0.0.1";
$username = "username";
$password = "Password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users(id, name, profilepath, picpath) VALUES (NULL, '$uname','$picpath', '$profilepath')";
if ($conn->query($sql) === TRUE) {
echo "New record created!";
}
else {
echo "Error.";
}
$conn->close();
?>
From the following HTML/JS:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script>
$('.button').click(function(){
var unameValue = $('input:text').val();
var actionValue = $(this).val();
var ajaxurl = 'upload.php',
data = {
'uname': unameValue,
};
$.post(ajaxurl, data, function(response) {
alert("success!!!!");
});
});
</script>
</head
<body>
<form method="POST">
<input id="userinput" type="text" name="uname" value="peter" />
</form>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" class="button" value="submit" />
</form>
</body>
</body>
</html>
However when I run the code I see that two html files have been created(when only wanting one). What is more, they are named differently (e.g. user1.html, user2.html). Also when I check the MySQL database the following appears:
ID Name picpath profilepath
1 Peter usertest/user1.html uploads/img19ckdovj239si.
2 usertest/user2.html uploads/img19ckdovj239si.png
3 George usertest/user3.html uploads/img19ckdovuv34yu.
usertest/user4.html uploads/img19ckdovuv34yu.png
And so on(the random image numbers are made up). It is really weird! I should also add that sometimes the two images would have the same uniqid()(as seen above) and sometimes they wouldn't.
I tried everything I could find online, but it seems like nobody has encountered this problem!
Any help would be greatly appreciated!
Thanks!
EDIT:
This is what the html should look like (it's much simpler, and without js!):
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload"/>
<input id="userinput" type="text" name="uname" value="peter" />
<input type="submit" class="button" value="submit" />
</form>
</body>
</body>
</html>
It uses the same PHP.
actually is not weird! you send data twice! (with post and ajax!) so your form send twice. Clear ajax function or action and method from form tag like this :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script>
$('.button').click(function(){
var unameValue = $('input:text').val();
var actionValue = $(this).val();
var ajaxurl = 'upload.php',
data = {
'uname': unameValue,
};
$.post(ajaxurl, data, function(response) {
alert("success!!!!");
});
});
</script>
</head
<body>
<form method="POST">
<input id="userinput" type="text" name="uname" value="peter" />
</form>
<form >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" class="button" value="submit" />
</form>
</body>
</body>
</html>

Upload Code Not Working in PHP

Have got an HTML and a PHP to upload the image to the server. I have used this same code previously and it works fine but I dont know why it is not working now,
Or its maybe the place where I am using the code is not appropriate. Below are the codes.
HTML to take input from user
<form action ="login.php" method="POST">
<label >USername :</label><br/>
<input type="text" name ="userid" /><br/>
<label >Password :</label><br/>
<input type="password" name="pid" /><br><br/>
<input type="submit" value ="Login" />
</form>
PHP for login.php
<?php
$x = 1;
while($row = mysqli_fetch_array($result)){
echo $x.'<br/>';
?>
//Form to upload the image
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="image" name="img" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
</form>
<script type="text/javascript">
function uploadInage()
{
var file_data = $('#image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "file.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 (result) {
alert(result)
}
});
}
</script>
<?
echo "-------------------------------------------------------".'<br/>';
$x = $x+1;
}
print_r($stores,$stores_add,$stores_chain,$jobs);
}
?>
PHP to upload File
file.php
<?php
$imagePath = "uploads/";
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename = $_FILES["file"]["tmp_name"];
$time = time();
move_uploaded_file($filename, $imagePath . $time . '.' . $extension);
echo "File Uploade";
exit;
?>
Kindly tell me why this code doesnt work.
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="image" name="img" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function uploadInage()
{
var file_data = $('#image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "file.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 (result) {
alert(result)
}
});
}
</script>
Thanks to I'am Back.
Just added jquery.min.js and it works completely fine.
Paste this code in login.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
I guess you are using ajax so you have to convert this file to DataUrl to send it by ajax
var fileInput = document.getElementById('YourInputID');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
$("#myTextAreaID").val(reader.result)
}
reader.readAsDataURL(file);
}
});
It will convert your file to data url and before save it on a textarea now you can send it by ajax
to convert it to an image at php script use
convert_data_url($data_url,$idFile,$folder) {
$image = base64_decode(str_replace('data:image/png;base64,','',$data_url));
save_to_file($image,$idp,$size,$pasta);
}
function save_to_file($image,$idFile,$folder) {
if(!file_exists($folder)){
mkdir($folder);
}
$fp = fopen($folder."/".$idFile.".jpg", 'w');
fwrite($fp, $image);
fclose($fp);
}
So you have to use this function convert_data_url($data_url,$idFile,$folder)
where data_url is the image
id idFile is the name that you want
and folder where you want to save it.

Popup message and ajax to jquery form

I create a form with PHP and jQuery, I add this in footer of my website, all I need is to display the form results in a popup in the main of my website not in the footer and make this to work without page refresh (with ajax). I add here my entire code:
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<?php
if(isset($_REQUEST['submit'])) {
$url = $_REQUEST['url'];
if(substr( $string_n, 0, 7 ) != "http://" && substr( $string_n, 0, 8 ) != "https://")
$url = "http://".$url;
if(stripos($url,"folder/")>0)
$content = file_get_contents($url);
else
$content = file_get_contents($url."/folder/");
if(preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : ".$result[1];
else
echo "Sorry cannot determine year";
}
?>
EDIT
dont forget to put jquery in top of the html page
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
Check below solution
//this will be your html file
<form id="form1" enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<script>
$(function() {
$('#form1').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(html) {
alert(html);
}
});
});
});
</script>
create a post.php file put your php code
<?php
if (isset($_REQUEST['submit']))
{
$url = $_REQUEST['url'];
if (substr($string_n, 0, 7) != "http://" && substr($string_n, 0, 8) != "https://")
$url = "http://" . $url;
if (stripos($url, "folder/") > 0)
$content = file_get_contents($url);
else
$content = file_get_contents($url . "/folder/");
if (preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : " . $result[1];
else
echo "Sorry cannot determine year";
}
?>
If you are only using the code provided, you are still missing some AJAX code. As you have used both the jQuery and JavaScript tags, I wasn't sure if you are using Vanilla or jQuery (my example uses jQuery).
My example will make an AJAX request when the user clicks the submit button. $your_url will need to be set to a file which contains your PHP code you specified in the question.
$('#my_button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
text: $('#some_text').val(),
},
url: "<?php echo $your_url; ?>",
success: function(data) {
console.log($data);
}
});
});
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text" / id="some_text">
<input type="submit" name="submit" value="Check" class="btn btn-primary" id="my_button" />
</form>
Your PHP will need to be changed so that it works correctly with this AJAX request. As mentioned in the comments, it seems like you do not fully understand how AJAX works, and how it communicates with PHP. I suggest the following documentation and tutorials:
AJAX documentation
AJAX beginners guide

upload a file in the same page as the form using php and ajax not working

Trying to upload a file using php/ajax but seems like its not working, maybe its not recognizing the $_FILES["file_name"]["tmp_name"] variable in the upload_file.php because I could not display it in the page.
Can you please help!
index.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="upload_file.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_name" id="file_name" />
<input type="submit" name="submit" value="RUN" id ="btnSubmit">
</form>
<div id='upload_here_div'></div>
upload_file.js
$(document).ready(function(){
console.log(file_name +'uplooad');
$('#btnSubmit').click(function(e) {
console.log('click trigger');
var file_name = $("#file_name").val();
$("#upload_here_div").load("upload_file.php?file_name=" + client_info )
console.log('value for file_name=' + file_name ); //
});
});
upload_file.php
<?php
$file_name = $_REQUEST['file_name'];
if ( isset($_FILES["file_name"])) {
//if there was an error uploading the file
if ($_FILES["file_name"]["error"] > 0) {
echo "Return Code: " . $_FILES["file_name"]["error"] . "<br />";
}
else {
$file_locatioon = "upload/".$file_name ;
echo 'file_locatioon = '.$file_locatioon."<br>";
move_uploaded_file($_FILES["file_name"]["tmp_name"], $file_locatioon);
echo "ploaded!!<br>";
}
} else {echo "No file selected <br />";}
?>
I found this tutorial before and tested OK. By using FormData may give what you want.
But please take the browser compatibility in consider. For more information please reference here.
I think you get a same problem with this jQuery Ajax File Upload.
Maybe it is helpful for you.

Photo Upload not working via Ajax call

I am trying to upload a photo using Ajax so that photo can be posted after clicking of submit button.
Flow:
user uploads image -> Ajax call is made to upload photo,
user clicks submit -> Post is shown to the user along with photo
Here is my php file for upload image:
<div class="box-footer">
<div id='preview' style="max-width:50px;max-height:60px;padding:5px;></div>
<div id="button_bar">
<!-- <div id="icons">
<div class="filebutton" title="Image Upload"> -->
<form id="imageform" method="post" enctype="multipart/form-data" action='WallPost1/ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg" onchange= PhotoUpload()></span>
</form>
</div>
<button type="submit" class="btn btn-primary" id="tweet_submit" onclick=TweetSubmit()>Submit</button>
</div>
</div>
Here is my JS code:
function PhotoUpload(){
alert ('got photo');
$("#preview").html('');
$("#preview").html('<small>Loading...</small>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
}
Here is my ajax_image.php code
<?php
include('includes/dbconnection.php');
include("session.php");
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif","JPG","JPEG","jpeg","PNG");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$command="Insert into uploads(image_name) values('$actual_image_name')";
if (!mysqli_query($con,$command))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
//echo "-----Images here----".$msg;
$query=mysqli_query($con,"Select upload_id,image_name from uploads where image_name='$actual_image_name'");
$result=mysqli_fetch_array($query);
$id=$result['upload_id'];
echo "<img src='BootStrapProject/WallPost1/uploads/".$actual_image_name."' class='preview' id='$id'>";
}
else
echo "failed";
}
else
echo "Image file size max 250k";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
Whenever i select a file using the input form, JS is called and i see 'loading...' message on UI but nothing happens after that.
Can somebody help me to understand why my ajax_image.php file is not being called.
Thanks in advance!
I was ale to solve the problem, i beleive the issue was that JQuery library was somehow overridden with older version which did not support ajaxForm.
Thanks for all your valuable inputs.

Categories