Somehow it just doesnt upload the image to the folder. It goes so far as adding to the database (what model is all about) however no upload.
I hope to know what im doing rong. See my code bellow
The
HTML
<div class="dropzone infile dz-clickable" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" id="file" type="file" multiple />
</div>
</div>
JS
var myDropzone = new Dropzone("#my-dropzone", {
url: admin_url+'add_image/material',
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sending",function(file, xhr, formData){
file.token = Math.random().toString(36).substr(2,9);
formData.append("token",file.token);
formData.append("type", file.type);
formData.append("size", file.size);
});
this.on("complete", function (file) {
console.log(file);
});
this.on("successmultiple", function(file, response) {
console.log(file);
});
this.on("errormultiple", function(file, response) {
console.log(file);
});
this.on("removedfile",function(file){
var token = file.token;
$.ajax({
type:"post",
data:{token:token},
url: admin_url+'remove_image',
cache:false,
dataType: 'json',
success: function(res){
}
});
});
},
dictDefaultMessage: "<div class='drag-icon-cph'><i class='material-icons'>touch_app</i></div><h5>Plaats hier bestanden om te uploaden</h5>",
dictRemoveFile : "Bestand verwijderen"
});
PHP (Codeigniter)
public function add_image($type, $rel_id = 0){
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
$path = getcwd() . '/uploads/';
$tmpFilePath = $_FILES['file']['tmp_name'];
if (!empty($tmpFilePath) && $tmpFilePath != '') {
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
$extension = strtolower($extension);
$allowed_extensions = array(
'jpg',
'jpeg',
'png'
);
if (!in_array($extension, $allowed_extensions)) {
set_alert('warning', 'PHP blocked file extention');
return false;
}
$filename = uniqid(rand(), true).'.'.$extension;
$newFilePath = $path . '/' . $filename;
// Upload the file into the upload dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $newFilePath;
$config['new_image'] = $filename;
$config['maintain_ratio'] = true;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
$CI->image_lib->resize();
$CI->image_lib->clear();
$data = array(
'rel_type' => $type,
'rel_id' => $rel_id,
'attachment_key' => $this->input->post('token'),
'file_name' => $filename,
'filetype' => $this->input->post('type'),
'size' => $this->input->post('size'),
'dateadded' => date('Y-m-d H:i:s')
);
$id = $this->back_model->add_image($data);
if($id != ''){
array_push($_SESSION['tmp_image'],$id);
}
unlink($newFilePath);
}
}
}
}
The folder uploads is created and for security i added a empty index.html file.
.htaccess is standard Codeigniter
Related
How can i upload multiple images instead of one, uploading one image works now this is what i am using. I have uploaded many images with Laravel and blade, but with vue im not sure on how to achieve this
Vue Template
<input type="file" v-on:change="onImageChange" multiple />
In Vue Script
onImageChange(e) {
// console.log(e.target.files[0]);
this.image = e.target.files[0];
},
SubmitProducts(e) {
e.preventDefault();
const config = {
headers: { "content-type": "multipart/form-data" },
};
let formData = new FormData();
formData.append("image", this.image);
axios
.post("/admin/products", formData, config)
.then((result) => {
var v = this;
v.showalert = true;
setTimeout(function () {
v.showalert = false;
}, 3000);
})
.catch((err) => {
console.log(err);
});
},
ProductController
public function store(Request $request)
{
DB::beginTransaction();
try {
$image = $request->file('image');
$fileName = 'products' . time() . '.' . $image->getClientOriginalExtension();
Storage::disk('uploads')->put($fileName, file_get_contents($image));
$product->image = $fileName;
$product->save();
DB::commit();
return response()->json('Product successfully inserted');
}
Hello there
Hope you will be doing good.I want to download txt file generated on the fly from the controller of laravel i have search alot but could not find any solution.Please help out i will be very thankful.
Blade code with axios request
submitHandler:function(form,e){
var btn=document.querySelector("#BtnSubmit");
btn.style.display="none";var img=document.createElement("img");
img.setAttribute("src",base_url+'front/images/loading.gif');
var loader=document.querySelector("#loader");loader.appendChild(img);
var url="<?php echo route('database.export-txtProcess');?>";
var cur_url="<?php echo route('database.export-txt');?>";
//var tblExportSelect = $("#tblExportSelect").val();
var pushArray = [];
$.each($("#tblExportSelect option:selected"), function(){
pushArray.push($(this).data("id"));
});
var data = new FormData();
data.append('tblExportSelect',pushArray);
//$("#tblExportSelect").val(selected);
axios({
method: 'POST',
url: url,
data: data,
})
.then(function(res){
console.log(res);
})
e.preventDefault();
}
});
Controller Method
public function exportTxtProcess(Request $request){
/*dd($request->tblExportSelect);*/
$tables = explode(",", $request->tblExportSelect);
$destinationPath = public_path('/');
$result;
foreach ($tables as $table) {
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table."-".$today;
$fp = fopen($destinationPath . "$fileName.txt","wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table,$output);
fwrite($fp,$netResult);
}
$result = fclose($fp);
}
/*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
echo json_encode($arr);*/
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$downloaded = response()->download($pathToFile)->deleteFileAfterSend();
}
}
I want to download when txt file which is created as above but instead of download it streaming in the console.
Thank in advance
You have to pass the headers. Most importantly you are not returning the reponse.
$headers = [
'Content-type' => 'text/plain',
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Length' => sizeof($content)
];
return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();
I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
I'm trying to upload an image from a WYSIWYG textarea (TinyMCE), but it's not working, it gives me the error "File not selected".
I'm using multipart form, is it conflicting with other "input file" ?
Thanks.
Here is the code i'm using.
View (.twig)
{{ form_open_multipart() }}
...
<div class="form-group">
<label class="col-sm-2 control-label">Texto</label>
<div class="col-sm-10">
{{ form_textarea('text',set_value('text') ? set_value('text') : post.text|raw,'class="form-control editor"') }}
<input name="image" type="file" id="upload_img_wysiwyg" class="hidden" onchange="">
</div>
</div>
{{ form_close() }}
Controller
public function upload_image_tinymce() {
//Check whether user upload picture
if (!empty($_FILES['image']['name'])) {
$config['upload_path'] = ADDONPATH.'themes/escolamagica/img/escolamagica-blog/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['image']['name'];
$config['overwrite'] = TRUE;
$config['max_size'] = '10240';
$config['max_width'] = '10000';
$config['max_height'] = '10000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image')) {
$picture = str_replace('\\', '/', base_url().'img/escolamagica-blog/'.$_FILES['image']['name']);
} else {
echo 'CONFIG';
var_dump($config);
echo 'IMAGE';
var_dump($_FILES);
echo 'ERROR';
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die;
$picture = '';
}
} else {
$picture = '';
}
return $picture;
}
Javascript
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text: '',
icon: 'image',
onclick: function(e) { // when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on("change", function(e){
uploadFile($(this), editor);
});
}
function uploadFile(inp, editor) {
var input = inp.get(0);
var data = new FormData();
data.append('image[file]', input.files[0]);
$.ajax({
url: BASE_URL + 'admin/blog/upload_image_tinymce',
type: 'POST',
data: data,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
console.log(data);
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.responseText) {
errors = JSON.parse(jqXHR.responseText).errors
alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
}
}
});
}
tinymce.init({
language: "pt_PT",
language_url: BASE_URL + "/admin/js/pt_PT.js",
selector: ".editor",
height: 600,
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern"
],
toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link imageupload",
toolbar2: "print preview media | forecolor backcolor emoticons",
image_advtab: !0,
setup: function(editor) {
initImageUpload(editor);
}
You are using a different index for the upload in your form and the tinyMce image upload. Your html form has file input with the name "image". But your MCE ajax file upload has the name "pic". So, in your controller function upload_image_tinymce() replace $_FILES['image'] with $_FILES['pic']
Use this in controller :
public function upload_image_tinymce() {
//Check whether user upload picture
if (!empty($_FILES['pic']['name'])) {
$config['upload_path'] = ADDONPATH.'themes/escolamagica/img/escolamagica-blog/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['pic']['name'];
$config['overwrite'] = TRUE;
$config['max_size'] = '10240';
$config['max_width'] = '10000';
$config['max_height'] = '10000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('pic')) {
$picture = str_replace('\\', '/', base_url().'img/escolamagica-blog/'.$_FILES['pic']['name']);
} else {
echo 'CONFIG';
var_dump($config);
echo 'IMAGE';
var_dump($_FILES);
echo 'ERROR';
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die;
$picture = '';
}
} else {
$picture = '';
}
return $picture;
}
I checked if file exists using Input::hasFile('File'), and it returns true and successfully got file's binary.
But Input::file('File')->getClientOriginalExtension() returns empty string.
Here's my controller
public function ConfirmWrite()
{
if (!Session::has('id')) {
return '0:Please log in.';
}
$Data = Request::all();
$Data['uid'] = Session::get('id');
$Data['mid'] = 0;
var_dump(Input::file('File')->getClientOriginalExtension());
return '1';
if (Input::hasFile('File')) {
$file = Input::file('File');
$rules = ['File' => 'mimes:jpeg,bmp,png,jpg|max:10000'];
$validator = Validator::make(['File' => $file], $rules);
if ($validator->fails()) {
return '0:Check your File.';
}
$Data['Thumbnail'] = $file->getClientOriginalExtension();
$destinationPath = 'images/post/thumbnail/';
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
$upload_success = $file->move($destinationPath, $Content . '.' . $Data['Thumbnail']);
echo "asdfasdfasdf : ".$Data['Thumbnail'];
if ($upload_success) {
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 320, 'small');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 700, 'medium');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 1920, '');
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
} else {
return '0:Somethings wrong';
}
} else {
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
}
}
And below code is Front-end Ajax code.
var fData = new FormData;
GlobalVar.Thumbnail == '' ? '' : fData.append('File', DataURLtoBlob(GlobalVar.Thumbnail));
fData.append('Title', $('.contents-details').find('h1').html());
fData.append('Subtitle', $('.contents-details').find('h2').html());
fData.append('Content', $('#post-editor').froalaEditor('html.get'));
fData.append('Align', EditorAlign);
fData.append('Tag', Tag);
fData.append('Share',GlobalVar.FBShare);
$.ajax({
url: '{{ URL::to('/post/write') }}',
type: 'post',
processData: false,
enctype: "multipart/form-data",
contentType: false,
cache: false,
data: fData,
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function (result) {
var Check = $.trim(result).split(':');
$('.submit-loading').css('display', 'none');
if (Check[0] == '1') {
checkUnload = false;
location.href = '{{ URL::to('post') }}/' + Check[1];
} else {
console.log(result);
Warning(Check[1]);
}
},
});
I can't find where is bug code and mistake I made. Please help me. This make me mad.
The getClientOriginalExtension method returns the extension of the actual file uploaded some-image.pdf, this is not considered a safe value. Instead you could best use guessExtension.
The guessExtension method uses the actual mime type and returns the related file type.