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...`
}
Related
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
/>";
}
}
?>
I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}
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
}
});
});
});
i've case to use variable more the one like code bellow :
function upload(iddata,ring)
{
//variable 1
dataString ="iddata="+iddata+"&ring="+ring+""; // variable 1
//variable 2
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
// i want put both variabel in ajax like this
$.ajax({
data: {formData,dataString}, //variable 1 and 2 in group
});
}
please how source is True
You should handle your whole data as an object only, and not mix it as a string and a array in a object. In this case you would not get the expected data in your receiver.
You could change it like this:
function upload(iddata, ring) {
var data = {
iddata: iddata,
ring: ring,
formData: new FormData()
};
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
data.formData.append("file[]", file, file.name);
}
$.ajax({
data: data
});
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MyBird extends CI_Controller {
/**
* Index Page for this controller.
function add_bird()
{
// get user id posted
$iddata=empty($_POST['iddata']) ? '' : $_POST['iddata'];
$ring=empty($_POST['ring']) ? '' : $_POST['ring'];
//echo json_encode(array('uploaded' => 'Oke Bos'));
if ( ! empty($_FILES))
{
$config['upload_path'] = "./assets/images/uploads";
$config['allowed_types'] = 'gif|jpg|png|mp4|ogv|zip';
$this->load->library('upload');
$files = $_FILES;
$number_of_files = count($_FILES['file']['name']);
$errors = 0;
// codeigniter upload just support one file
// to upload. so we need a litte trick
for ($i = 0; $i < $number_of_files; $i++)
{
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = "Ring".$ring._.$Random_Number; //new file name
$config['file_name'] = $NewFileName;
$_FILES['file']['name'] = $files['file']['name'][$i];
$_FILES['file']['type'] = $files['file']['type'][$i];
$_FILES['file']['tmp_name'] = $files['file']['tmp_name'][$i];
$_FILES['file']['error'] = $files['file']['error'][$i];
$_FILES['file']['size'] = $files['file']['size'][$i];
// we have to initialize before upload
$this->upload->initialize($config);
if (! $this->upload->do_upload("file")) {
$errors++;
}
}
if ($errors > 0) {
echo $errors . "File(s) cannot be uploaded";
}
}
}
}
in controller i put code like bellow, but the filen can't move upload
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;
});