I have been attempting to get a nice neat file upload using ajax, and from the many items on SO I have been able to get the framework done as follows:
My HTML:
<form enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input type="button" value="Upload" />
Pretty straight forward.
My PHP storeSales.php
if ($_FILES["file"]["name"] != NULL) {
if (file_exists("accounting/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"], "accounting/" . $_FILES["file"]["name"]);
}
}
$file = fopen($_FILES['myfile']['name'],'r') or die('cant open file');
and my .js:
$(":button").click(function(){
var formData = new FormData($('form')[0]); if (formData !=null) {
alert("Got the file");
} else {
alert("nothing Here");
}
$.ajax({
url: 'storeSales.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(result)
{
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
When I try to upload a file, I get the alert in my .js file that says "Got the file" but in the php code I get the error that a file cannot be empty. From everything I have been able to find, I thought I was doing the php correctly. what is the correct way to handle this? Am I missing something else?
You can't use ajax to upload files - it's an illegal operation (via the dry Ajax route) without a third-party script. In short, you can't pass $_FILES data via Ajax. Only $_POST data. You need to find a plugin.
Try Uploadify:
http://www.uploadify.com/
Related
I have been trying to upload a file from my webpage to a folder on the server using jQuery and PHP.
Here is my JavaScript code for generating the file to send and then using a POST request to send the file to my PHP script so that it can then handle the file and save it to a particular folder.
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('Character', characterBlob);
//Communicate with the server
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // 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(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
Here is my PHP script to handle the sent file and save it in a specified folder.
<?php
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/Applications/AMPPS/www/webGL/upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
?>
When I try to send the file from my webpage nothing appears in the 'Upload' folder that I am trying to save the file to.
Could someone please tell me why a file is not saved in the 'Upload' folder? I am eventually looking to open this file in a Maya application on the server and run some Python code. Would I even need to save the file on the server before opening it in Maya? Or could I open Maya with the file straight away?
Try use my code and tell me if it works. This should work if you adapt it to your filenames and input, and other elements ids, it's tested by me:
$('#upload').on('click', function(e) {
$('#message').fadeOut();
e.preventDefault();
if ($('#file')[0].files.length == 0) {
alert('Choose a file!');
} else {
var file_data = $('#file').prop('files')[0]; //file object details
var form_data = new FormData($('#form')[0]);
form_data.append('file', file_data);
var unique_identifier = $('#unique_identifier').val();
$.ajax({
url: 'upload.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(php_script_response) {
$('#message').html(php_script_response).fadeIn();
//alert(php_script_response); // display response from the PHP script, if any
}
});
}
});
<form id='form' action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='unique_identifier' id='unique_identifier' placeholder='unique identfier' value="<?php echo rand(1000000, 9999999); ?>">
<input type='file' name='file' id='file' />
<a id='upload'>Upload</a>
</form>
And the PHP script I made:
$unique_identifier = (isset($_POST['unique_identifier']))?trim($_POST['unique_identifier']):'';
$upload_directory = 'upload/' . $unique_identifier . '/';
if (!file_exists($upload_directory)) {
mkdir ($upload_directory, 0777);
}
$original_filename = basename($_FILES['file']['name']);
$destination = $upload_directory . $original_filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination)
Also, I recomend you to do some PHP validation.
It seems you are not appending the file to uploaded to the form data, May be you need something like this.
var elem = $(this).val() // lets say this is the element where you uploaded the photo
var formData = new FormData();
formData.append('file', elem[0].files[0]);
$.ajax({
url: "ExecuteMaya.php",
type: "POST",
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(result){
// your code executed successfully
}
I have made a form on my wordpress theme through which i want user to upload image .This is my HTML
<input type="file" id="file" />
<button id="uplod" ">Upload</button>
and below is my js
jQuery("#uplod").click(function()
{
console.log("trying to fetch image");
var selectedFile = jQuery('#file').get(0).files[0];
console.log(selectedFile);
var ajaxdata=
{
action:"reg_upload_img",
img:"selectedFile"
}
jQuery.post(ajaxurl, ajaxdata,function(res)
{
jQuery(".divError").html(res);
});
});
and my function in functions.php file of theme is
function fiu_upload_file(){
$error = '';
var_dump($_FILES);
wp_die();
}
add_action('wp_ajax_reg_upload_img', 'fiu_upload_file');
add_action('wp_ajax_nopriv_reg_upload_img', 'fiu_upload_file');
what should i add in my js code and php code so that image of form can be passed to my wordpress directory so that i can save and handle it in wp database
You can't upload files with jQuery.post(), only XMLHttpRequest can be used with FormDataand jQuery.ajax() can be used which uses XMLHttpRequest internally.
jQuery("#uplod").click(function(e) {
e.preventDefault();
var fd = new FormData($("#file"));
fd.append("action", "reg_upload_img");
fd.append("img","selectedFile");
$.ajax({
url: url,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
});
and a small typo with your button's attributes, you have an extra ":
<button id="uplod">Upload</button>
//----------------^-----------one extra '"' removed from here.
So, I have the following form and js/php:
php
<form enctype="multipart/form-data">
<input id="fileupload" type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/>
<input type="button" class="submit_form" value="submit">
</form>
<?php
add_action( 'wp_ajax_UploadImage', 'UploadImage' );
function UploadImage()
{
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
//Some function
}
?>
JS
function UploadImage(e)
{
jQuery('#fileupload').fileupload({
url: upload_image.ajax_url,
});
if(jQuery('#fileupload')) {
var form = document.forms.namedItem("upload_video");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
jQuery.ajax({
success : function(data){
alert('sddsf');
}
})
}
};
As you can see from here, when an image is selected using Blueimp jQuery File upload (which the js is not properly written), I want the image file to be handled by the php function.
In other words, the js is not correctly written and I am not sure how to initiate the plugin then when the image is selected, it is processed by the php function via ajax (meaning, how do I parse the file info to php function via ajax?)
Don't use $.ajax directly. The plugin already does that behind the scenes.
Here's a working example, based on your code, but adapted to run on JSFiddle:
$(document).ready(function(){
var url = '/echo/json/';
var formdata = {json: JSON.stringify({field1: 'value1'})};
jQuery('#fileupload').fileupload({
url: url,
formData : formdata,
dataType: 'json',
type: "POST",
contentType:false,
processData:false,
success : function(data){
alert('success...');
console.dir(data);
}
});
});
Demo: http://jsfiddle.net/pottersky/8usb1sn3/3/
I am trying to save a loaded image on Server Using jQuery,Ajax and PHP.
Here is the code I have for Ajax part:
<script>
$(function () {
$("#uploadimage").on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
var imgloader = $.ajax({
type: "POST",
url: "imgLoader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formData);
}
});
imgloader.fail(function () {
console.log('Error');
});
imgloader.done(function (data) {
$('#res').text(data);
});
});
});
</script>
and I have this PHP on imgLoader.php
<?php
if (isset($_FILES["file"]["type"])) {
$file = $_FILES['file']['tmp_name'];
$newloc = "newupload/" . $_FILES['file']['name'];
move_uploaded_file($file, $newloc);
} else {
echo 'There is Something Wrong?!';
}
?>
but I am getting the
There is Something Wrong?!
on the page without uploading the image on server. Can you please let me know what I am doing wrong? (I know this is not a secure and safe way to upload image to server, but please be informed that I am trying to lean the whole process of uploading without validation, sanitizing or filtering)
Thanks
AJAX doesn't do file uploads. It's not designed for that. For uploading files without page refreshing you will have to use any jquery ajax plugin.For e.g.
http://www.malsup.com/jquery/form/
This problem is already discussed in following link:
PHP and Ajax file upload - Can't get the tmp_name with $_FILES
I am trying to upload images via an AJAX call and Codeigniter:
My View:
<?php echo form_open_multipart('upload/do_upload'); ?>
<input type="file" name="userfile" id="userfile" size="20" />
<br />
<input type="submit" value="upload" id="upload_file_1" />
</form>
My Ajax Call:
$(document).ready(function(){
$(function() {
$('#upload_file_1').click(function(e) {
e.preventDefault();
var filename = $("#userfile").val();
$.ajax({
url :'index.php/upload/do_upload',
secureuri :false,
fileElementId: 'userfile',
dataType : 'json',
type : 'POST',
done : function (data)
{
alert(data);
}
});
});
});
});
and my controller:
class Upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$this->load->view('upload_form', array('error' => ' '));
}
function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '10240';
$config['max_height'] = '7680';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
echo "error!";
echo "<pre>";
print_r($error);
echo "<pre/>";
} else {
echo "done!";
}
}
}
but it gives me an error saying : "You did not select a file to upload. "; without AJAX it works fine, probably my AJAX call is not right! Could you please let me know if I am doing something wrong?
Thanks
In my very recent project i used below code to upload files with formdata asynchronously using jquery ajax,
However i was not able to upload files with success: function() of jQuery so i used complete to process server response. You can try with success:function().
You will receive your data in $_Post & file in $_FILES variable.
If only want to upload files. change it like wise.
Hope this will help you.
Also look at this tutorial:http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
function frm_submit(){
var form = new FormData(document.getElementById('frmSample')); //frmSample is form id
var file = document.getElementById('userfile').files[0]; //userfile file tag id
if (file) {
form.append('userfile', file);
}
$.ajax({
url: 'path/to/upload/script',
type: 'POST',
xhr: function() { // custom xhr
//progressHandlingFunction to hangle file progress
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: form,
cache: false,
contentType: false, //must
processData: false, //must
complete: function(XMLHttpRequest) {
var data = JSON.parse(XMLHttpRequest.responseText);
console.log(data);
console.log('complete');
},
error: function() {
console.log('error');
}
}).done(function() {
console.log('Done Sending messages');
}).fail(function() {
console.log('message sending failed');
});
}//function frm_submit ends here
i used this javascript library
https://github.com/blueimp/jQuery-File-Upload
and got file uploading working with ajax - drag/drop + progress bars, and returns the appropriate file icon or image thumbnail that could be downloaded straight away. it was quite difficult to get it fully working and abstracted so the same routine handled multiple types of uploads each with their own restrictions.
the link will give some basic example code, it is worth a look.
pete