It tells me The filetype you are attempting to upload is not allowed.
$config['upload_path'] = './' . URL_FILES_ALUMNOS;
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
$config['file_name'] = uniqid();
$this->load->library('upload', $config);
$this->upload->initialize($config);
I've readed in SO that it may be missing this:
'pdf' => array('application/pdf', 'application/force-download', 'application/x-download', 'binary/octet-stream')
But is not missing.
I don't know if another portion of code is needed to figure out what's happening
Thanks
You should try this code. i hope it will work for you
form data is
<div class="form-group">
<label for="pdf1">File input</label>
<input type="file" id="pdf1" name="pdf1">
</div>
AJAX CODE
$(document).on('submit','#form_id',function(event){
event.preventDefault();
var pdf1= $('#pdf1').val().split('.').pop().toLowerCase();
if(jQuery.inArray(pdf1, ['gif', 'png', 'jpg', 'jpeg','pdf']) == -1)
{
alert("invalid File extention");
$('#pdf1') . val('');
return false;
}
$.ajax({
url: "<?php echo base_url();?>Home/upload_pdf",
method: 'POST',
data: new FormData(this),
contentType: false,
processData: false,
success: function(data)
{
}
});
});
CONTROLLER FUNCTION
function upload_pdf(){
$id = $this->input->post('img_id');
$content = array(
'text1' => $this->input->post('text1'),
'text2' => $this->input->post('text2'),
'img2' => $this->upload_pdf_function()
);
// insert this array here;
}
public function upload_pdf_function()
{
if(isset($_FILES['img2']))
{
$pdf1= explode('.', $_FILES['pdf1']['name']);
$new_name = rand().'.'.$pdf1[1];
//$destination = '/vendor_images'.$new_name;
move_uploaded_file($_FILES['pdf1']['tmp_name'], 'directory_name/folder_name/'.$new_name);
return $new_name;
}
}
Related
I am using ajax to send a request to a laravel controller with multiple images and other,
Everything work on local environement but when I upload to the production environement, the upload fails with the error
Failed to load resource:/property/images/add:1 the server responded with a status of 403 ()
Here is the ajax code
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()}
});
$('#images').change(function () {
event.preventDefault();
let image_upload = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
let images = $('#images')[0];
let p_id = $('input[name=p_id]').val();
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images[]', images.files[i]);
}
image_upload.append('TotalImages', TotalImages);
image_upload.append('p_id', p_id);
$.ajax({
method: 'POST',
url: '{{ route('image.add') }}',
data: image_upload,
contentType: false,
processData: false,
success: function (images) {
Swal.fire(
'Success!',
'Images uploaded successfully',
'success'
);
$('#images').reset();
},
error: function () {
Swal.fire(
'Failed!',
'An error occured please try again',
'error'
);
$('#images').reset();
}
});
});
and this is the controller code
public function store(Request $request)
{
//check if an image has been selected
if ($request->images) {
$total=$request->TotalImages;
$images = $request->images;
foreach($images as $image) {
$photo = new Photo;
$photo->p_id = $request->p_id;
$image_temp = $image;
//echo $image_temp; die;
if ($image_temp->isValid()) {
$extension = $image_temp->getClientOriginalExtension();
$filename = 'bks'.mt_rand(000, 9999999999) . '.' . $extension;
$filepath = 'uploads/property/large/' . $filename;
$webimagefilepath = 'uploads/property/small/' . $filename;
//upload the image
Image::make($image_temp)->resize(600, 600)->save($filepath);
Image::make($image_temp)->resize(200, 200)->save($webimagefilepath);
$photo->path = $filename;
$photo->alt_text = "Book sasa property image";
$photo->save();
}
}
}
return response()->json("Success");
}
I am using named routes and the name is the one used in the ajax url.
What could I be doing wrong and how can I solve it?
I am not able to upload any images after second input. I can only upload the first input. The inputs are created dynamically when another input value is added. Below is the code:
\\ jquery //
function storeupdate(){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>updatestore",
data:$("#mainstore").serialize(),
success: function(response){
var data = new FormData();
input = document.getElementById('file');
for(var i = 0; i < input.files.length; i++)
{
data.append('images[]', document.getElementById('file').files[i]);
}
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>storeupload',
cache: false,
contentType: false,
processData: false,
data : data,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
});
swal('Successful!', 'Data has been saved!', 'success');
//window.location.reload();
},
error: function() {
swal("Oops", "We couldn't connect to the server!", "error");
}
});
return false;
};
\\ view //
<input type="file" name="images[]" id="file" class="file" accept="image/*;capture=camera" multiple="multiple" />
<button type="button" class="btn btn-success save" id="save" name="save" onclick="storeupdate();" disabled>Save</button>
\\ controller //
public function storeupload()
{
$files= $_FILES;
$cpt = count ($_FILES['images']['name']);
for($i = 0; $i < $cpt; $i ++) {
$_FILES['images']['name'] = $files['images']['name'][$i];
$_FILES['images']['type'] = $files['images']['type'][$i];
$_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
$_FILES['images']['error'] = $files['images']['error'][$i];
$_FILES['images']['size'] = $files['images']['size'][$i];
$this->upload->initialize ( $this->set_upload_options1() );
$this->upload->do_upload("images");
$fileName = $_FILES['images']['name'];
$images[] = $fileName;
}
}
I made and tested a little sample of code so that you can see what's wrong. You have a few things wrong. First thing I would recommend is actually using jQuery. Your code is obviously using jQuery, but you have all kinds of vanilla JS that can be simplified:
$(document).ready(function(){
$('#save').on('click', function(){
var fileInput = $('#file_input')[0];
if( fileInput.files.length > 0 ){
var formData = new FormData();
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
$.ajax({
method: 'post',
url:"/multi_uploader/process",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
}else{
console.log('No Files Selected');
}
});
});
Notice that I hard coded in the ajax URL. The controller I used for testing was named Multi_uploader.php.
Next is that in your controller when you loop through the $_FILES, you need to convert that over to "userfile". This is very important if you plan to use the CodeIgniter upload class:
public function process()
{
$F = array();
$count_uploaded_files = count( $_FILES['images']['name'] );
$files = $_FILES;
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES['userfile'] = [
'name' => $files['images']['name'][$i],
'type' => $files['images']['type'][$i],
'tmp_name' => $files['images']['tmp_name'][$i],
'error' => $files['images']['error'][$i],
'size' => $files['images']['size'][$i]
];
$F[] = $_FILES['userfile'];
// Here is where you do your CodeIgniter upload ...
}
echo json_encode($F);
}
This is the view that I used for testing:
<!doctype html>
<html>
<head>
<title>Multi Uploader</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/js/multi_uploader.js"></script>
</head>
<body>
<form>
<input type="file" name="images[]" id="file_input" multiple />
<button type="button" id="save">Upload</button>
</form>
</body>
</html>
Finally, just to prove that the files were uploaded to the controller, and that I could use them with CodeIgniter, I send the ajax response as a json encoded array, and display it in the console. See the code comment where you would put your CodeIgniter upload code.
UPDATE (to show what to do with multiple file inputs) ---
If you want to have multiple file inputs, then that obviously changes your HTML and JS a bit. In that case, your HTML would have the multiple inputs:
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
And your javascript needs to change to loop through each input:
$(document).ready(function(){
$('#save').on('click', function(){
var fileInputs = $('.file_input');
var formData = new FormData();
$.each(fileInputs, function(i,fileInput){
if( fileInput.files.length > 0 ){
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
}
});
$.ajax({
method: 'post',
url:"/multi_uploader/process",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
});
A little more info about your comment regarding adding the details to your database ---
When you do an upload with CodeIgniter, there is a provided upload summary:
$summary = $this->upload->data();
This is an array of data that ends up looking like this:
$summary = array(
'file_name' => 'mypic.jpg',
'file_type' => 'image/jpeg',
'file_path' => '/path/to/your/upload/',
'full_path' => '/path/to/your/upload/jpg.jpg',
'raw_name' => 'mypic',
'orig_name' => 'mypic.jpg',
'client_name' => 'mypic.jpg',
'file_ext' => '.jpg',
'file_size' => 22.2
'is_image' => 1
'image_width' => 800
'image_height' => 600
'image_type' => 'jpeg',
'image_size_str' => 'width="800" height="200"'
);
So all you would have to do to add a record to your database is this after each upload:
$summary = $this->upload->data();
$this->db->insert('storefiles', array(
'Store_ID' => $_POST['storeid'],
'File_Name' => $summary['file_name'],
'Created' => date('Y-m-d h:i:s'),
'Modified' => date('Y-m-d h:i:s')
));
It's pretty easy to see that you could store a lot more than just the filename.
I know this question is old, but for people like me who encounter this error: is_uploaded_file() expects parameter 1 to be string, array given after using the Code Igniter file upload library within the loop like so:
for ( $i = 0; $i < count($var); $i++ )
{
// other codes here
// Do codeigniter upload
$this->upload->do_upload('images');
}
What you can do is to not put any params in the do_upload() function. Like so:
$this->upload->do_upload();
I am using laravel framework 5.2. I have successfully implemented dropzone and i have also done with upload images. Now problem is that when i want to delete the image from folder it gives me error. I think my code is not right for deleting image.
Here is my add Upload image Function i have uploaded images in session:-
public function addContributorimages(Request $request){
if($request->ajax()){
$image=$_FILES['file'];
if(!empty($image)){
if($image['error']==0){
$name = pathinfo($_FILES['file']['name']);
$ext = $name['extension'];
$rand=str_random(24).'.'.$ext;
$destination = base_path() . '/public/images/ContributorImages/';
if(is_uploaded_file($image['tmp_name'])){
list( $width, $height, $source_type ) = getimagesize($image['tmp_name']);
if ($width >= 10 && $height >= 10){
move_uploaded_file($image['tmp_name'],$destination.$rand);
$request->session()->put('contributorimage.'.str_random(5).'.image',$rand);
$images = $request->session()->get('contributorimage');
echo "<pre>"; print_r($images);
}
else{
echo "Error";die;
}
}
}
}
}
}
This is my add Function of images
Here is my dropzone code :-
Dropzone.autoDiscover = false;
var fileList = new Array;
var i =0;
$("#my-awesome-dropzone").dropzone({
method:'POST',
maxFiles: 10,
paramName: "file",
maxFilesize: 10,
addRemoveLinks: true,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
clickable: true,
init: function() {
// Hack: Add the dropzone class to the element
$(this.element).addClass("dropzone");
this.on("sending",function(file, xhr, formData) {
formData.append("_token", "{{ csrf_token() }}");
});
this.on("success", function(file, serverFileName) {
fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
//console.log(fileList);
i++;
});
this.on("removedfile", function(file) {
var rmvFile = "";
for(f=0;f<fileList.length;f++){
if(fileList[f].fileName == file.name)
{
rmvFile = fileList[f].serverFileName;
if (rmvFile){
$.ajax({
type: 'POST',
url: '../contributor/delete-subimages/'+rmvFile,
});
}
}
}
});
},
url: '../contributor/add-subimages',
});
});
My images are successfully uploaded but i want to remove the image from session as well as from folder can anyone help me how to do that
Here is my delete function of image:-
public function deleteContributorImage(Request $request,$name = null){
$imageName=explode('.',$name);
$imageRandomName = $request->session()->get('contributorimage.'.$imageName[0].'.image');
$destination = base_path() . '/public/images/ContributorImages/';
if(unlink($destination.$imageRandomName)){
$request->session()->forget('contributorimage.'.$imageName[0]);
echo "success";
}
else{
echo "failed";
}
}
Now when i upload images it create this sesssion now i am having two images in session
Array
(
[Dkf08] => Array
(
[image] => whywu3dprVPKKkhUgdIMAdLQ.jpg
)
[rH5NV] => Array
(
[image] => i2sZEqjMdiQHcKRyy5Km9vlu.jpg
)
)
can anyone hlep me how to slove this issue . Thanks in advance :)
you have to create one hidden filed for that and when you remove file from dropzone than that file name should be save in that hidden filed.
myDropzone.on('removedfile', function (file) {
var hidden_filed= document.getElementById('hidden_filed').value;
if (alreadyRemove == "") {
$('#deleteImage').val(file.name);
} else {
$('#deleteImage').val(hidden_filed+ ',' + file.name);
}
});
after that get that field as POST data in controller. From file name you can delete Image as usual.
Created a normal upload image system and uploaded the image to the database now when i click on upload the image does not show itself on the div assisgned but i have to reload the page again to see that uploaded image what can i use to show the image with ajax submit
here is the code
<div id="timelineProfilePic"><?php
{
$image_properties = array('src'=> base_url("uploads/" . $image_file),'width' => '200px','height'=> '200px','id'=>'profilepic','rel' => 'lightbox');
echo img($image_properties);
?>
<div id="profilepicselector">
<?php echo form_open_multipart('',["id"=>"form_profile"]); ?>
<input type="hidden" name="id" value="<?php echo $id ;?>" >
<?php echo form_upload(["name"=>"imagefile"]); ?>
<?php echo form_submit(["name"=>"submit","value"=>"Submit"]); ?>
<?php echo form_close(); ?>
</div>
<?php
}
?></div>
jQuery('#form_profile').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/do_upload"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
$('#profilepic').attr('src',data);
},
error: function(data){
//error function
}
});
});
public function do_upload()
{
$config = [
'upload_path' => './uploads',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 1100000000,
'max_width' => 102400000,
'max_height' => 76800000,
];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('imagefile'))
{
$post = $this->input->post();
unset($post['submit']);
//print_r($post);
$upload_data = $this->upload->data();
print_r($upload_data);
$file_name=$_FILES['imagefile'];
$this->load->model('Pmodel');
$this->Pmodel->upload_model($post,$file_name);
$image_path_profile= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
}
else
{
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/profile',compact('upload_error'));
}
}
found the error it was a silly mistake. i needed to echo the image path so that it will change when i click on ajax submit at the end like this
echo $image_path_profile= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
this will return the image at the same time i am uploading it.
thanx for your reply
I'm using laravel 4.2 and currently I don't how to save a csv file into public\csv\ directory using AJAX. I'm still finding some answers. Maybe someone can help me with this.
Here's my code:
In blade view:
{{Form::open(['route' => 'file_upload', 'files' => true, 'id' => 'upload_form', 'method' => 'POST'])}}
{{Form::file('csv_upload', ['id' => 'uploaded_file', 'accept' => 'text/csv'])}}
{{Form::submit('submit', ['class' => 'btn btn-primary btn-xs', 'id' => 'upload'])}}
{{Form::close()}}
Javascript Ajax:
var ajax_ready = 1
var token = {{Session::get('_token')}}
if($.type(originalOptions.data) === 'string') {
options.data = originalOptions.data+"&_token="+token;
}else if($.type(originalOptions.data) === 'object') {
//Here I got a new error
}else{
options.data = $.param(($.extend(originalOptions.data, {'_token':mmad_token})));
}
options.url = originalOptions.url.slice(0,originalOptions.url.indexOf("?_token="));
if (ajax_ready!=1){
jqXHR.abort();
}
ajax_ready = 0;
});
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var form = new FormData(this);
var csvFile = {lastModifed: csv[0].lastModified, fileName: csv[0].name, size: csv[0].size, fileType: csv[0].type};
$.post('{{ URL::route("file_upload") }}?_token={{Session::token()}}',{
data: form
}).done(function(response){
});
});
PHP:
public function upload_csv()
{
$inputs = Input::all();
$csvFile = $inputs['data']['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('csv/');
if(is_dir($path2))
{
#move_uploaded_file($csvFile, $path2.$csvFile); //This line can't move the uploaded files in my desired directory
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
This code below does work when not using AJAX:
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
$originalFilename = $file->getClientOriginalName();
$rules = ['csv_upload' => 'required|file:csv'];
$validate = Validator::make(['csv_upload' => $file], $rules);
if($validate->fails())
{
return json_encode(['error' => 1, 'description' => 'File must be in .csv format']);
}
$path = public_path('/csv/');
if(!file_exists($path))
{
mkdir($path);
}
}
Console.log of csv
You can not move file because when you submit form with ajax file is not being sent with ajax,For sending file you have to send file with FormData() javascript Object.
If you check in upload_csv controller by putting print_r($_FILES); you will get empty array.
So use FormData on client side for appending file, then try agian.
You aren't getting error beacuse you have used php Error Control Operators likes#move_uploaded_file($csvFile, $path2.$csvFile);.
if you need working example then tell me i will give it to you.
Code For Your Help:
1. In blade view:
<script type="text/javascript">
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="mmad_csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var formData = new FormData($(this)[0]);
formData.append('uploaded_file', $("#uploaded_file")[0].files[0]);
formData.append('lastModifed', csv[0].lastModified);
formData.append('fileName', csv[0].name);
console.log(formData);
$.ajax({
url: '{{ URL::route("file_upload") }}',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata) { //alert(returndata); return false;
}
});
});
</script>
2.Controller
public function file_upload(Request $request)
{
$inputs = Input::all();
$csvFile = $inputs['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('/csv/');
if(is_dir($path2))
{
$success = $request->file('uploaded_file')->move($path2, $csvFile);
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:
Input::file('fileName')->move($destinationPath, $fileName);
If you need additional validations, you can check it at http://laravel.com/docs/5.1/requests#files
Default AJAX POST does not support file uploads. Use jQuery Form to upload files successfully. Full documentation of file upload at http://malsup.com/jquery/form/#file-upload
Below my example of a recentlty build script... My Controller uploads the files to S3, but is easy to be implemented with local storage.
var progress = function(event, position, total, percent) {
$(".progress-bar").width(percent + '%');
$(".progress-bar").html(percent + '%');
if(percent > 50) {
$(".progress-bar").css('color','#fff');
}
if(percent == 100) {
setTimeout(function(){
$(".progress").html('<span class="processing-msg">Processing... Please be patient!</span>');
$(".processing-msg").fadeIn('slow');
}, 1000);
}
}
var success = function(data) {
var obj = $.parseJSON(data);
$("#"+obj.hidden, parent.document).val(obj.filename);
var src = 'https://s3.amazonaws.com/spincms'+obj.path+'thumb_'+obj.filename;
$("#uploaded-"+obj.hidden, parent.document).html('<img class="img-circle uploaded-img" src="' + src + '">');
$(".progress").html('<span class="processing-msg-next">File has been uploaded and processed. Do not forget to submit the form!</span>');
}
var options = {
target: '#output',
uploadProgress: progress,
success: success,
resetForm: true
};
$(document).on('click', "#upload-now", function(e) {
$(".progress").html('<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>');
if($("#upload-form input[type=file]")[0].files.length == 0) {
$(".progress").html('<span class="processing-msg-next">No file selected!</span>');
return false;
} else {
var name = $("#upload-form input[name='name']").val();
var token = $("#upload-form input[name='_token']").val();
var file_name = $("#upload-form input[type=file]")[0].files[0].name;
$("#upload-form").ajaxSubmit(options);
}
}
});
Since you are using jQuery you can use the form plugin as it will make things much more easier for you to work with for example , this is the jquery part that you will use :
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#upload_form').ajaxForm(function() {
alert("Your file has been uploaded, thanks");
});
});
and in your controller you can code it like :
pubilc function postUpload()
{
$success = false;
if(Request::ajax())
{
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
if(!File::isDirectory(storage_path('csv'))) {
File::createDirectory(storage_path('csv'));
}
$file->move(storage_path('csv'), $file->getClientOriginalName());
// now your file is on app/storage/csv folder
$filePath = storage_path('csv/'.$file->getClientOriginalName());
$success = true;
}
}
return Response::json(['success'=>$success]);
}