AJAX to PHP Image Upload - javascript

I am attempting to upload multiple images from AJAX to PHP. Here's a run down of what I have so far.
HTML
<form>
<input class="images" type="file">
</form>
There could be more than one input field if the user has multiple images to upload.
Javascript
var imageObject = GetAllFiles($('.images'));
function GetAllFiles(_selector)
{
var newObject = {};
for (var i = 0; i < $(_selector).length; i++)
{
var elem = $(_selector)[i];
newObject[i] = $(elem).files;
}
return newObject;
}
$(document).on('click', '#submit', function() {
var _data = JSON.stringify(imageObject);
$.post('upload.php', { action: 'ImageUpload', data: _data }, function (e){
alert(e);
});
)};
Send data via AJAX after conversion to JSON
PHP
if(isset($_POST['action']))
{
$action = $_POST['action'];
switch($action)
{
case 'ImageUpload' : ImageUpload($_POST['data']); break;
}
}
function ImageUpload($jsonData)
{
$images = json_decode($jsonData);
foreach($images as $image)
{
$directory = "../images/maschine/";
$target_file = $directory . basename($_FILES[$image])['name'];
if (move_uploaded_file($_FILES[$image]["tmp_name"], $target_file))
{
echo('Success');
} else
{
echo('Failure');
}
}
}

Add id in the file input first, and remember the enctype='multipart/form-data' in form.
<input class="images" name="file[]" type="file" multiple>
after that in the script
<script>
$('YoursubmitbuttonclassorId').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
</script>
In the php file
<?php
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br
/>";
}
}
?>

Related

Ajax post has previous data

This is driving me crazy. I know I am doing something wrong but what? The problem is I am getting previous data in my ajax call when I post it to php.
Story: I click upload button which calls JavaScript loadme() where i am cleaning the input type file element. I then select file/files and click upload which calls doit() which internally calls uploadFiles(). UploadFiles makes an array with loaded images and post it to the php file through ajax.
I have tried plain javascript and jquery to clean file input element and php to set post values to null after using it, but still i am getting the previous values.
The form
<form id="theform" method="post" action="" enctype="multipart/form-data" target="multifile">
<input type="hidden" id="folderpath" name="folderpath" value="<?=htmlspecialchars($path)?>">
<input name="upfiles[]" id="upfiles" type="file" multiple="" />
</form>
Javascript
async function doit(){
//some code
uploadFiles();
}
function loadmeup(){
$('upfiles').value = '';
$('uploadbox').show();
}
function closeupload(){
$('uploadbox').hide();
}
var masterFileArray = [];
var left_loaded_count = 0;
var progress = 0;
function uploadFiles() {
var files = document.getElementById("upfiles").files;
var path = document.getElementById('folderpath').value;
var numOfFiles = files.length;
alert(numOfFiles);
if (files && numOfFiles>0) {
for (var i = 0, f; f = files[i]; i++) {
if(checkExtension(f.name) && checkSize(f.size)){
progress = i+1/numOfFiles;
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
var contents = e.target.result;
masterFileArray.push({name:f.name, contents: contents, type:f.type, size:f.size});
console.log(f.name);
left_loaded_count -= 1;
if(left_loaded_count == 0)
{
var filesarray = null;
filesarray = JSON.stringify(masterFileArray);
console.log("after stringify: "+filesarray.length);
new Ajax.Request('upload_do.php', {
method: 'post',
parameters: {files: filesarray, folderpath:path},
onSuccess: function(transport){
var response = transport.responseText;
parent.notify(response);
closeupload();
get_listview(currlist,sort);
}
});
}
};
})(f);
left_loaded_count += 1;
r.readAsDataURL(f);
}
else{
alert('Invalid file extension or size ' + f.name);
if(progress==0)
location.reload();
}
}
} else {
alert('Failed to load files');
closeupload();
}
}
PHP
try{
$error = null;
$files = json_decode($_POST['files'],true);
$numFiles = 0;
foreach($files as $file){
$output = $reso->writeUpload($file['contents'], $file['name']);
$numFiles++;
}
}
catch (Exception $ex){
$error = $ex->getMessage();
$GLOBALS['log']->log($error);
}
isset($_POST['files'])? $_POST['files'] = null: '';
if (!is_null($error))
echo _($error);
else
echo _($numFiles.' file'.(($numFiles > 1) ? 's' : '').' successfully
uploaded');

Multiple file attachments to php via ajax

Before you judge me please know that I am not a big pro and just trying to learn how to do things here.
I am trying to create a mailing form with multiple attachments
form code
<div class="file-upload-wrapper">
<label class="file-field" data-max-files="6">
<input type="file" name="photos[]" multiple>
<span>Drag your files here or click to select your files <span>.jpg, .png and .pdf</span></span>
</label>
<div class="uploaded-files"></div>
</div>
js/jQuery code
var photos = [];
var data;
$(document).ready ( function() {
//Documnet Upload Script//
function fileUpload(obj){
var dropZone = obj.find('.file-field');
var fileInput = dropZone.find('input[type="file"]');
var filesBeen = obj.find('.uploaded-files');
var maxFiles = Number(dropZone.attr('data-max-files'));
function highlightDropZone(e){
if(e.type == 'dragover') dropZone.addClass('highlighted');
else dropZone.removeClass('highlighted');
e.preventDefault();
return false;
}
function filesDropped(e){
highlightDropZone(e);
var files = e.target.files || e.dataTransfer.files;
for(var i = 0, file; file = files[i]; i++) {
if(file.size <= 3000000 && (file.type == "application/pdf" || file.type == "image/jpg" || file.type == "image/jpeg" ||file.type == "image/png")) {
photos.push(file);
if (file.type == "application/pdf") {
var uploaded = filesBeen.prepend('<div><div><img src="images/adobe-acrobat-pdf-file-512.png"></div><span></span></div>');
uploaded.find('span').click(function () {
$(this).closest('div').animate({width: 0, height: 0}, 200, function () {
$(this).remove()
});
});
} else {
var fReader = new FileReader();
fReader.onloadend = (function(f){
return function() {
if (maxFiles > Number(filesBeen.children('div').length)) {
var uploaded = filesBeen.prepend('<div><div><img src="' + this.result + '"></div><p><span>' + f.name + '</span></p><span></span></div>');
uploaded.find('span').click(function () {
var me = $(this);
$(this).closest('div').animate({width: 0, height: 0}, 200, function () {
$(this).remove();
me.unbind('click');
});
});
}
}
})(file);
fReader.readAsDataURL(file);
}
}else {
window.alert("The size of the file is more than 3Mb or format is not supported.");
}
}
console.log(photos);
}
dropZone.get(0).addEventListener('dragover', highlightDropZone);
dropZone.get(0).addEventListener('dragleave', highlightDropZone);
dropZone.get(0).addEventListener('drop', filesDropped);
fileInput.get(0).addEventListener('change', filesDropped);
}
$('.file-upload-wrapper').each(function(){
new fileUpload($(this));
});
$('.submit-form').click(function(e) {
e.preventDefault();
// Store values in variables
var form = $('form[name="contact-form"]');
var ip = form.find('input[name=ip]');
var httpref = form.find('input[name=httpref]');
var httpagent = form.find('input[name=httpagent]');
var name = form.find('input[name=name]');
var email = form.find('input[name=email]');
var phone = form.find('input[name=phone]');
var message = form.find('textarea[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
var emails = form.find('input[name=email]').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if (validateEmail(emails)) {
// Organize data
data = new FormData();
data.append('ip', ip.val());
data.append('httpref', httpref.val());
data.append('httpagent', httpagent.val());
data.append('name', name.val());
data.append('email', email.val());
data.append('phone', phone.val());
data.append('message', message.val());
data.append('submitted', submitted.val());
data.append('visitor', visitor.val());
for(var i = 0; i < photos.length; i++){
data.append('file'+i, photos[i]);
}
var request = $.ajax({
type: "POST",
dataType: 'script',
url: "/includes/sendConatctform.php",
data: data,
cache: false,
contentType: false,
processData: false,
success: function (html) {
if (html == "true") {
form.find('.email-sent').fadeIn(500).delay(4000).fadeOut(500);
} else {
form.find('.email-error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function (jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
} else {
form.find('.email-results').fadeIn(500).delay(4000).fadeOut(500);
}
return false;
});
});
What I am trying to do is to receive the attachments in my PHP file for further proceedings.
php code
$message = "Date: $todayis \r\n";
$message .= "From: $name ($email) \r\n";
$message .= "Phone: $phone \r\n";
$message .= "Subject: $subject \r\n";
$message .= "Message: $userMessage \r\n";
$message .= "IP Address: $ip \r\n";
$message .= "Browser Info: $httpagent \r\n";
$message .= "Referral: $httpref \r\n";
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}
I have tried the suggestion that I have found here Send multiple file attachments to php file using ajax
but it did not help with my situation.
can you please advise?
All help is appreciated
Thank you in advance
Since in your php code you are iterating over $_FILES['photos'], then you should change in your js code this:
data.append('file'+i, photos[i]);
to
data.append('photos[]', photos[i]);
Update:
Also, in your php code change $file['filename'] here:
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}
to just $file:
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" . $file;
}

AJAX File Upload using Codeigniter, jQuery shows the responce as "The action you have requested is not allowed"

I have an ajax file upload with jquery. It always shows The action you have requested is not allowed. Helper arrays html, url, file, form are added. I tried many ways, but gets the same result.
Here is my code
Controller Functions
function demo() {
$this->load->view('file_upload_ajax', NULL);
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
$config['max_size'] = '1024'; //1 MB
echo $_FILES['file']['name'];
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
View file: file_upload_ajax.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Beep Check</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="<?php echo base_url().'js'?>/beep.js"></script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
</html>
beep.js
$(document).ready(function() {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: base_url +"beep/upload_file",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['base_url'] = '';
//$config['index_page'] = 'index.php';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
$config['url_suffix'] = '';
$config['language'] = 'english';
$config['charset'] = 'UTF-8';
$config['enable_hooks'] = FALSE;
$config['subclass_prefix'] = 'MY_';
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
$config['log_threshold'] = 4;
$config['log_path'] = '';
$config['log_date_format'] = 'Y-m-d H:i:s';
$config['cache_path'] = '';
$config['encryption_key'] = 'kccna_mat_1';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
$config['global_xss_filtering'] = FALSE;
$config['csrf_protection'] = true;
$config['csrf_token_name'] = 'k4rm4_auth';
$config['csrf_cookie_name'] = 'k4rm4_auth';
$config['csrf_expire'] = 7200;
$config['compress_output'] = FALSE;
$config['time_reference'] = 'local';
$config['rewrite_short_tags'] = FALSE;
$config['proxy_ips'] = '';
Please help me Thanks in advance.
Check your config.php if $config['csrf_protection'] = TRUE;
If it is set to true you need to send csrf token with the ajax request.
Add this to your view page.
<input type="hidden" id="hidCSRF" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
In your js file do the below changes.
$(document).ready(function() {
$('#upload').on('click', function () {
var _csrfName = $('input#hidCSRF').attr('name');
var _csrfValue = $('input#hidCSRF').val();
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append(_csrfName, _csrfValue);
$.ajax({
url: base_url +"beep/upload_file",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});

How to upload music from array in codeigniter

I have music file to upload on database
and from view side I have addmore button for music input type file and I got that music's name like:
music1.mp3,music2.mp3,music3.mp3
After that I explode this above on controller file.
I don't know, is this correct?
$expaudio = explode(',',$audio);
$audioCount = count($expaudio);
if($audioCount == 0){ $audiolist = $audio; }
else{ $audiolist = $expaudio; }
for($i=0; $i<$audioCount; $i++){
//******************************* UPLOAD MUSIC ********************************//
$config['allowed_types'] = 'avi|mpeg|mp3|mp4|3gp|wmv'; //video and audio extension
$config['max_size'] = '40000000';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
//$video_name = random_string('numeric', 5);
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 10; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$video_name = $randomString;
$config['file_name'] = $video_name;
$config['upload_path'] = 'Users/'.$data['loginuserpage'].'/music/'.$project_url.'/audio';
//$config['allowed_types'] = 'gif|jpg|jpeg|png|doc|docx|ppt|pptx|pdf|txt|avi|mpeg|mp3|mp4|3gp|wmv'; // Image , video and audio
$this->load->library('upload', $config);
if (!$this->upload->do_upload($audiolist[$i]))
{
$error = array('error' => $this->upload->display_errors());
$vid_url = '';
print_r($this->upload->display_errors());
}
else
{
$upload_data = $this->upload->data();
$aud_name = $upload_data['file_name'];
$aud_type = $upload_data['file_type'];
$aud_url = $baseurl.$config['upload_path']."/".$aud_name;
}
//******************************* UPLOAD MUSIC ********************************//
}
My Ajax file
$("input[name='audio[]']").change(function()
{
var temp =[]
$("input[name='audio[]']").each(function(i, selected){
texts = $(selected).val()
temp.push(texts);
var jcat1 = temp.join(",");
alert(jcat1);
$('#audioarr').val(jcat1);
});
});
$('form#music').submit(function(e)
{
e.preventDefault();
var form = $(this);
/*var purl = form.find('#project_url').val();
if (purl.length < 8) {
$('p#purl').html('Please enter a url without space and specialchar');
return false;
}*/
var video = form.find('#video').val();
var trailer = form.find('#trailer').val();
dataString = $("form#music").serialize();
$.ajax({
url: '<?php echo base_url('video/creations/createmusic'); ?>',
type: "POST",
data: dataString,
data: new FormData(this),
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) { $("#success").html(data); }
});
});
You don't need to use for loop for uploading multiple files.
Since you are storing all file details in single array, use can use
$this->upload->do_upload('audio'); // input file name
You can access uploaded file details from
$data = $this->upload->data();
foreach($data as $audio) {
`// code goes here...`
}

How Do Upload With angularjs In Codeigniter

im sorry mr im try this code for upload with angular in codeigniter but file and data not insert to database and file not upload, :)
please corectly im no find that tutorial in google please..
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
$config['upload_path'] = 'assets/img/img_berita/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if( ! $this->upload->do_upload($data($_FILES['file'])) ) {
$this->set_model->update_data('berita', array('gambar' => $data['file']['name']), array('id_berita' => $data['id_berita']) );
echo '{"stat" : "Success!"}';
} else {
echo '{"stat" : "Try Again!"}';
}
app.controller('berita_uploadImage', function($scope,$http,$routeParams,$location,Upload) {
$scope.ImageInfo =
$scope.dataInfo = [];
$scope.onFileSelect = function(file) {
//console.log($scope.picFile);
if (!file) return;
console.log(file);
Upload.upload({
method : 'POST',
url : '<?php echo base_url();?>home/dashboard/admin/upload_image_berita',
data : JSON.stringify({'id_berita':$scope.id_berita,file:file}),
}).success(function(data) {
console.log($scope.id_berita);
console.log(file);
console.log(data.stat);
});
}
$scope.id_berita = $routeParams.id_berita;
$http.get('<?php echo base_url(); ?>home/dashboard/admin/getImage_berita/' + $scope.id_berita ).success(function(result) {
$scope.dataInfo = result;
});

Categories