PHP AJAX UPLOAD? - php

I am having problem uplaoding file,
here are my codes:
Any help? Thanks!
test.html
function insertPhoto()
{
var description = document.getElementById('description').value;
var image = document.getElementById('photo').value;
var url = "ajax_insert.php?action=add&image="+image+"&description="+description;
var ajaxRequest = ajax_obj();
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4){
document.getElementById("msgbox").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
return false;
}
<div align="center">
<div class="top" >
<div>
Decription <input name="description" type="text" id="description" value="" maxlength="20" />
</div>
<div style="margin-top:5px" >
Image
<input name="photo" type="file" id="photo" value="" maxlength="20" />
</div>
<div class="buttondiv">
<input name="button" type="button" value="Upload" onclick="return insertPhoto()" style="margin-left:-10px; height:23px" />
<span id="msgbox" style="display:none"></span>
</div>
</div>
</div>
ajax_insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('priceless');
define('DIR_IMAGE','images/');
$image = $_GET['image'];
$description = $_GET['description'];
$dbtable = 'photos';
$action = $_GET['action'];
if($action == 'add'){
$photo = '';
if ($_FILES[$image]['name']) {
$aray = explode(".",$_FILES[$image]['name']);
$ext = $aray[count($aray)-1];
$photo = date('Ymdhis').'.'.$ext;
move_uploaded_file($_FILES[$image]['tmp_name'],DIR_IMAGE.$photo);
}
$data = array(
'image'=> $photo,
'description'=> $description
);
$values = array();
foreach($data as $show){
$values[] = $show;
}
$query = "INSERT INTO ".$dbtable." (`".implode("`,`",array_keys($data))."`) values ('".implode("','",array_values($values))."')";
if ($result= mysql_query($query) or die(mysql_error())) {
echo "You have Sucessfully Upload Photo!";
}
}
?>

Personally I use this Ajax upload http://valums.com/ajax-upload/ and I'm satisfied with results.

You can't upload files using pure AJAX, because you can't access the file's contents programmatically due to security issues.
You can use an iframe and specify it as the target of the upload form.
You can see an example of it here: http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

You can't upload files using pure AJAX, because you can't access the file's contents programmatically.
You would have to use a different technique, e.g. submitting the form the normal way into a hidden iframe element. That's the way the jQuery form plugin does it.

If you want some AJAXy upload, look at Uploadify - http://www.uploadify.com/
It can handle multiple uploads at once, and has a real time progress bar. It then has JS parameters to allow you to handle the upload etc.
If you need a full tutorial give me a shout and I will show you some examples!
Hope this helps.

Because of security issues, many browsers do not let you pass data from a file select field through javascript/ajax. It is better to use a page that calls itself, with a normal submit button. (I've tried AJAX uploads on my own website, so believe me).
Try -
<?php
if ($_FILE['file'] != ''){
$dest = 'folder/';
list($name, $ext) = explode('.', $_FILES['file']['name']);
if(is_uploaded_file($_FILES['file']['tmp_name'])){
#move_uploaded_file($_FILES['file']['tmp_name'], $dest.$name.'.'.$ext);
};
};
?>

Related

how to upload at new name and section

I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>

Dynamically adding input file object with form

I designed a form in form.php with a file input. When I press +input button, a new file input object should be generated and save them to my mysql server.
My code here,
form.php
<div id="enterReplyReferenceList">
<div class="enterReplyRefInputContainer">
<div class="enterReplyRefInput">
<form action="submit.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $userID; ?>" name="userID">
<input type="submit" value="SEND"/>
<input type="file" name="enterRefFile[]" multiple class="enterRefFile" accept="application/pdf,image/jpeg, image/png, image/jpg"/>
</form>
</div>
</div>
</div>
<button onclick="appendRef()">+input</button>
form.js
function appendRef(){
var inputclass = document.getElementsByClassName('enterReplyRefInputContainer')[0];
var inputclassChild = document.createElement('div');
inputclassChild.innerHTML = inputclass.innerHTML;
var newClass = document.getElementById("enterReplyReferenceList").appendChild(inputclassChild);
newClass.className = "enterReplyRefInputContainer";
submit.php
for($i=0; $i<count($_FILES['enterRefFile']['name']); $i++) {
$tmpFilePath = $_FILES['enterRefFile']['tmp_name'][$i];
if ($tmpFilePath != ""){
$fileData = addslashes(file_get_contents($_FILES['enterRefFile']['tmp_name'][$i]));
$fileName = addslashes($_FILES['enterRefFile']['name'][$i]);
$fileType = $_FILES['enterRefFile']['type'][$i];
if($fileData != null){
if($fileType == "application/pdf" || $fileType == "image/png" || $fileType == "image/jpeg" || $fileType == "image/jpg"){
mysql_query("INSERT INTO attachment (attachData, dataType, attachName, userID) VALUES('$fileData','$fileType','$fileName', '$userID')");
}
}
}
}
When I pressed the +input button, a new input file object is generated with the same look with the original and I can select the files. However, only a single file can be uploaded to my mysql db after I clicked the submit button. Can somebody tell me why the new file input cannot be uploaded? Is the new objects will not be sent?
The problem is that your input button is cloning your whole div, which has the form, so when you click "Submit" you're uploading one form with one file element. Here's an updated version (all in one file, you can separate to your liking):
<button onclick="appendRef()">+input</button><br><hr>
<form action="submit.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $userID; ?>" name="userID">
<div id="enterReplyReferenceList">
<div class="enterReplyRefInputContainer">
<div class="enterReplyRefInput">
<input type="file" name="enterRefFile[]" multiple class="enterRefFile" accept="application/pdf,image/jpeg, image/png, image/jpg"/>
</div>
</div>
</div>
<hr>
<input type="submit" value="SEND"/>
</form>
<script>
function appendRef(){
var inputclass = document.getElementsByClassName('enterReplyRefInputContainer')[0];
var inputclassChild = document.createElement('div');
inputclassChild.innerHTML = inputclass.innerHTML;
var newClass = document.getElementById("enterReplyReferenceList").appendChild(inputclassChild);
newClass.className = "enterReplyRefInputContainer";
}
</script>
Button click is outside of the form so you don't do a submit action on it (unless you want to use a blocking action like jQuery preventDefault(), and you only need one submit for the whole form.

PHP-Jquery image upload not working

I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot

Attachments added through JavaScript function are not sent

I am using the following loop to send/attach multiple attachments to my email message.
foreach(array_keys($_FILES['attachment']['name']) as $key) {
$source = $_FILES['attachment']['tmp_name'][$key];
$filename = $_FILES['attachment']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
But only the first attachment i made is sended.
The form code is
<form method="POST" action="<?php $PHP_SELF ?>" enctype="multipart/form-data">
<input type="file" name="attachment[]" id="attachment" size="30"
onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;">
Attach another File</div>
<input name="submit" type="submit" value="submit" />
</form>
When one click on Attach another file, another File Upload button is shown, through a JavaScript function:
<script type="text/javascript">
var upload_number = 1;
var attachmentlimit = 5;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "attachment"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
if(upload_number == attachmentlimit) {
document.getElementById('moreUploadsLink').style.display='none';
}
}
</script>
Only the file attached through the first FileUpload Button is attached and sended, not the others.
Help.
The problem is that you are setting the name attribute of your new input element to attachment1, attachment2, etc. You should be setting this name to attachment[], just like the original input you created.
If you still don't get all your attachments, you can try a var_dump($_FILES) in your PHP script to ensure that you are getting all the files the way you expect them.

PHP Remote Image Process to save image on my server using the Picup App for mobile safari

I can't get the image to save in the /image_upload/uploads/ folder (then I can hopefully figure out the rest).
This is the code I got from parorrey.com
<?php
//remote image to copy
$remoteImageURL = 'http://www.mywebsite.com/image.jpg'; //I'm not sure what URL should be here
//local directory to store image
$dir_path = 'http://www.mywebsite.com/image_upload/uploads/';
if($remoteImageURL)
{
require_once('class.get.image.php');
// initialize the class
$image = new GetImage;
// just an image URL
$image->source = $remoteImageURL;
$image->save_to = $dir_path; // with trailing slash at the end
$get = $image->download('curl'); // using cURL
$pic = $dir_path.basename($remoteImageURL);
//you can use the picture path e.g. Insert into DB from this variable $pic
?>
This is some of the code for the PICUP application
<script>
var currentParams = {}
document.observe('dom:loaded', function()
{
$(document.body).addClassName('iphone');
// We'll check the hash when the page loads in-case it was opened in a new page
// due to memory constraints
Picup.checkHash();
// Set some starter params
currentParams = {
'callbackURL' : 'http://mywebsite.com/upload_pic5.php',
'postURL' : 'http://www.mywebsite.com/image_upload/picup_remote_image.php',
'referrername' : escape('mywebsite'),
'referrerfavicon' : escape('http://mywebsite.com/kwboat.ico'),
'purpose' : escape('Select your photo for our App.'),
'debug' : 'false',
'returnThumbnailDataURL': 'true',
'thumbnailSize' : '150'
};
Picup.convertFileInput($('photo'), currentParams);
});
</script>
<script type="text/javascript">
window.name = "fileupload";
</script>
This is my form code
<form action="save.php" method="post" id="add_boat">
<div class="step_bar_info">Upload a Picture of your boat</div>
<div id="image_box">
<div id="upload_area">
<?php if (isset($image_url))
{
echo '<img src="' . $image_url .'" />';
}
else
{
echo '<img src="images/boat.png" width="150px"/>';
} ?>
</div>
<input type="file" name="photo" id="photo"/><br />
Please select your photo to upload, you will need to install Picup App (Free) from iTunes. <br /><br /> Picup is a free iPhone app that facilitates photo uploads to our web app. Since Mobile Safari doesnt support file-upload form fields
<?php $image_url=($pic); ?><!-- gets from image processor though maybe should just change $pic -->
</div><!--image box-->
<input type="hidden" id="image_url" name="image_url" value="images/boat.png"/>
<div id="titlebox">Boats name<br/><input name="title" type="text" size="24" maxlength="60" value="" tabindex="1"></div><!--endtitlebox-->
<div id="info_box">Info<br/><textarea name="info" cols="20" maxlength="100" rows="2" tabindex="6"></textarea></div>
<input id="add_boat" type="submit" name="add_boat" value="save " alt="submit" title="Save item in our secure database system " />
</form>
Just from looking at your code I would like to say. If your choose file button is not showing up on your form.
In the picup currentParams. Picup.convertFileInput($('photo'), currentParams);
"photo" is intended to be your id="" name="" not "image_url"
Try
// initialize the class
$image = new GetImage();
Or its a typo?

Categories