How Do Upload With angularjs In Codeigniter - javascript

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;
});

Related

AJAX to PHP Image Upload

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
/>";
}
}
?>

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
}
});
});
});

My controller url disappears when i use ajax as login

I am developing a site that has a login form and a newsfeed. when i use ajax as my action to submit values to the controller my controller url disappears instead of having mypage/newsfeed
here is the script im using
$('#submitButton').on('click',function(){
var userid = $('#studentID').val();
var password = $('#password').val();
$('#errorHandler').empty();
var URL = '<?php echo base_url('newsfeed')?>';
if(userid.trim()!='' || password.trim()!=''){
$.ajax({
type:'POST',
url: URL,
data:{userid:userid,password:password},
success:function(data){
if(data)
$("body").load(data);
},error:function(errorw){
if( errorw.status == 400 ) { //Validation error or other reason for Bad Request 400
var json = $.parseJSON( errorw.responseText );
}
$('#errorHandler').append($('<label class="red-text text-darken-2">'+json+'</label>'));
}
});
}else{
$('#errorHandler').append($('<label class="red-text text-darken-2">ID/Password is Required</label>'));
}
});
UPDATE: controller code i am using custom routes $route['newsfeed'] = 'Login/Login';
public function Login(){
$userid = $this->input->post('userid');
$userpw = $this->input->post('password');
$validate = $this->loginmodel->validateAccount($userid,$userpw);
if($validate == NULL){
$this->output->set_status_header('400');
$details = $this->data['message'] = 'Incorrect Login/Password';
echo json_encode($details);
}
else{
$data['details'] = $this->loginmodel->getUserType($userid);
if(is_array($data) || is_object($data)){
foreach ($data as $key => $value) {
$type = $value->accounts_type;
}
}
$this->session->set_tempdata('accountID', $userid,18000);
$userid = $this->session->tempdata('accountID');
$data['init'] = $this->loginmodel->getGroups($userid);
$data['groupId'] = $userid;
if($type == "STUDENT"){
$data['details'] = $this->loginmodel->getDetails($userid);
$token = array(
'accountid' => $userid,
'groups' => $data['init'],
'details' => $data['details'],
);
$this->session->set_userdata($token);
$this->load->view('header');
$this->load->view('sidenav1', $data);
}
elseif($type == "PROFESSOR"){
$data['details'] = $this->loginmodel->getDetailsProf($userid);
$this->load->view('header');
$this->load->view('sidenav2', $data);
}
elseif($type == "ADMIN"){
$this->load->view('header');
$this->load->view('superadmin');
}
else{
$data['details'] = $this->loginmodel->getDetails($userid);
$this->load->view('header');
$this->load->view('Surveypage',$data);
}
}
}

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...`
}

PHP Image Upload Not Resizing When Sent Via JS

I am running into issues when uploading an image sent to PHP via JS. I can upload the image fine, but I would to resize the image before moving it to it's new destination. I can also rename the image without any issues. It's really just the resizing that is the issue here.
After a lot of searching I have seen a lot of questions regarding this on SO, which is how I got to where I am now, but not one that answers this 100%. If you know of a question/answer already on SO please link me to the correct article.
Any help is much appreciated, thanks.
Here is the JS
var test = document.querySelector('#afile');
test.addEventListener('change', function() {
var file = this.files[0];
var fd = new FormData();
fd.append('afile', file);
// These extra params aren't necessary but show that you can include other data.
fd.append('id', burgerId);
var xhr = new XMLHttpRequest();
// why wont this work in the actions directory?
xhr.open('POST', 'actions/upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var uploadProcess = document.getElementById('uploadProcess');
uploadProcess.setAttribute('style', 'width: ' + percentComplete + '%;');
// uploadProcess.innerHTML = parseInt(percentComplete) + '% uploaded';
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
image = 'img/' + resp.newFileName;
sessionStorage.setItem('burgerLoc', image);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
// upImage(id)
}, false);
Here is the markup
<input type="file" name="afile" id="afile" accept="image/*"/>
Here is the PHP
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($image_tmp);
} else if($ext == 'png') {
$src = imagecreatefrompng($image_tmp);
} else {
$src = imagecreatefromgif($image_tmp);
}
$file_content = file_get_contents($image_tmp);
$data_url = 'data:' . $image_type . ';base64,' . base64_encode($file_content);
list($width,$height) = getimagesize($image_tmp);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
// rename the file
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = '../img/' . $new_file_name;
imagejpeg($img_dest,$new_file_name,100);
move_uploaded_file($image_tmp, $new_file_location);
imagedestroy($src);
imagedestroy($img_dest);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
I would maybe try installing ImageMagick in your linux distribution and try to use this function to resize the image
http://php.net/manual/en/imagick.resizeimage.php
I have reproduced your script on my webserver... I have made modifications and came up with this.
The most significant modification is that I am using exact paths in the file locations, and that I am moving the tmp file to a real file, load that real file, resize that real file instead of trying it to do with the tmp uploaded file.
PHP:
<?php
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
$outputfolder = "/var/www/html/wp-content/";
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = $outputfolder.$new_file_name;
move_uploaded_file($image_tmp, $new_file_location);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($new_file_location);
} else if($ext == 'png') {
$src = imagecreatefrompng($new_file_location);
} else {
$src = imagecreatefromgif($new_file_location);
}
list($width,$height) = getimagesize($new_file_location);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
$resizedLocation = $outputfolder."resized_".$new_file_name;
imagejpeg($img_dest,$resizedLocation,100);
imagedestroy($src);
imagedestroy($img_dest);
$file_content = file_get_contents($resizedLocation);
$data_url = 'data:image/jpeg;base64,' . base64_encode($file_content);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
?>
Your HTML/JS stays untouched.
Now this works for me flawlessly, the only thing you have to make sure
the $outputfolder is writeable by the linux user under which the webeserver executing the php script is runnging (typically web-data...)
My web server:
CentOS Linux release 7.0.1406 (Core)
php.x86_64 5.4.16-23.el7_0.3
apache x86_64 2.4.6

Categories