Image can not be displayed after upload using Angular.js - javascript

I have an issue. I can not display image after selecting using ng-file-upload from Angular.js. I have to upload multiple file here. I am explaining my code below.
<div ng-repeat="mul in mulImage">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px">Image{{$index+1}}:</span>
<div>
<input type="file" class="filestyle form-control" data-size="lg" name="upload_{{$index}}" id="bannerimage_{{$index}}" ng-model="file" ngf-pattern="'image/*'" accept="image/*" ngf-max-size="2MB" custom-on-change="uploadFile" ngf-select="onFileSelect($index,$file);">
<div style="clear:both;"></div>
</div>
<span class="input-group-btn" ng-show="mulImage.length>0">
<img ng-src="{{attchImage}}" name="pro" border="0" style="width:32px; height:32px; border:#808080 1px solid;" ng-if="mul.image !=null">
<input type="button" class="btn btn-success" name="plus" id="plus" value="+" ng-click="addNewImageRow(mulImage);" ng-show="$last"> <input type="button" class="btn btn-danger" name="minus" id="minus" value="-" ng-show="mulImage.length>1" ng-click="deleteNewImageRow(mulImage,$index);">
</span>
</div>
</div>
my controller side code is given below.
$scope.uploadFile = function(event) {
console.log('event', $scope.mulImage.length);
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(file);
}
};
$scope.imageIsLoaded = function(e) {
$scope.$apply(function() {
$scope.attchImage = e.target.result;
});
}
Here i need after selecting the image it should display inside image tag but failed to do that. Here is my plunkr code. Please help me to resolve this issue.

You used 'onFileSelect' in your view and defined $scope.onFileSelect1.
If I edit it the plunkersample runs for me.
Or am I missing something?

Related

How to preview image when upload to multiple forms

I have 2 image upload forms, when one is uploaded it should show a preview of the uploaded image. However, when I upload an image in one of the input forms, both forms display a preview of the last uploaded image. How do I make the preview only appear on the uploaded form?
Here's my code :
<div class="container">
<form action="save.php" method="post" enctype="multipart/form-data">
<!-- rows -->
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview1" class="img-thumbnail1">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img1" class="file1" id="file1">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image1" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview2" class="img-thumbnail2">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img2" class="file2" id="file2">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image2" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="btn_save" class="btn btn-success">Save</button>
</form>
</div>
<script>
$(document).on("click", "#select_image1", function() {
var file = $(this).parents().find(".file1");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName1 = e.target.files[0].name;
$("#file1").val(fileName1);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview1").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(e.target.files[0]);
});
// 2
$(document).on("click", "#select_image2", function() {
var file2 = $(this).parents().find(".file2");
file2.trigger("click");
});
$('input[type="file"]').change(function(el) {
var fileName2 = el.target.files[0].name;
$("#file2").val(fileName2);
var reader2 = new FileReader();
reader2.onload = function(el) {
// get loaded data and render thumbnail.
document.getElementById("preview2").src = el.target.result;
};
// read the image file as a data URL.
reader2.readAsDataURL(el.target.files[0]);
});
</script>
I've tried changing the script code, but it doesn't work. Please help. Thank you.

Codeigniter do_upload method is not working

I am working on a cms with Codeigniter. I am trying to upload file from system. I am receiving the file but the do_upload method is not working. There are similar questions on this topic, but none of the answers of them worked.
Here is my method:
public function fileupdate($productId=False){
$formData = $this->input->post();
if (isset($formData['activityNewFile'])) {
foreach ($formData['activityNewFile'] as $key => $value) {
$rndNumber = rand(1,500);
$fileLastName = sef_url($formData['activitynewfilename'.$value]);
// Set preference
$config['upload_path'] = '../assets/';
$config['allowed_types'] = 'pdf|doc|docx|xls|xlsx';
$config['max_size'] = '80960'; // max_size in kb
$config['file_name'] = $fileLastName;
$upFile = 'activitynewfile'.$value;
// Load upload library
$this->load->library('upload',$config);
// File upload
if($this->upload->do_upload($upFile)){
// Get data about the file
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$daData = array(
'productId' => $productId,
'productFileName' => $formData['activitynewfilename'.$value],
'productFile' => $filename
);
$productfileInsert = $this->db->insert('productfile',$daData);
}
}
}
$this->success("İşlem tamamlandı.");
}
HTML part:
<form class="m-form m-form--fit m-form--label-align-right" role="form" method="POST" id="product_file_edit" action="<?=base_url('product/product/fileupdate/'.$productInfo->productId);?>" enctype="multipart/form-data" onsubmit="return false; form_gonder('product_file_edit')" >
<div class="modal-body">
<div class="form-group m-form__group row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="col-md-12" style="margin-bottom: 10px;padding: 0;" id="file_row">
<button onclick="addFileRow('file_add')" class="btn btn-primary btn-sm">
<i class="zmdi zmdi-plus"></i> Add
</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button onclick="form_gonder('product_file_edit')" class="btn btn-green btn-sm">
Save
</button>
</div>
</form>
Javascript part:
function addFileRow(tur){
if(tur=="file_add"){
emreFile = Math.floor(Math.random() * 10);
myhtmlFile = '<div class="col-md-12 row" id="filenew'+emreFile+'" style="padding: 0;margin: 0;margin-bottom: 10px;"><div class="input-group"><input type="hidden" name="activityNewFile[]" value="'+emreFile+'"><img src="../assets/file/pdfword.png" style="width: 38px;float: left;height: 38px;"><input type="text" name="activitynewfilename'+emreFile+'" class="form-control" placeholder="Dosya Adı" style="width: 45%;float: left;height: 39px;"><input type="file" name="activitynewfile'+emreFile+'" accept=".xls,.xlsx,.doc,.docx,.pdf" class="form-control" placeholder="Dosya Adı" style="width: 46%;opacity: 1;float: right;position: relative;"><span class="input-group-btn"><button class="btn btn-red btn-fab btn-fab-sm animate-fab" onclick="deleteNewFileRow('+emreFile+')" type="button"><i class="zmdi zmdi-delete"></i></button></span></div></div>';
var icerikFile = myhtmlFile;
jQuery("#file_row").prepend(icerikFile);
}
}
I would be very grateful if you could find out what the problem is.
Your problem is actually the file is not loading properly. There is no error in your codes. Make sure file_uploads is turned on on your server. Make sure the upload_max_filesize value is not smaller than your file size.

I can't reset input file inside form after submit

I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";

Remove specific file from the input file list of array in php

I'm doing a multiple image upload with PHP. When doing the preview, I have provided the button to remove the image as well.
My code is as follow :
HTML
<div class="col-md-12 margin-bottom10">
<input type="file" accept="image/*" name="file_name[]" id="file_name" onchange="preview_image()" class="inputfile" multiple />
<?php echo '<div class="margin-bottom10">'.form_error('file_name').'</div>'; ?>
<label class="btn btn-danger" for="file_name"><i class="fa fa-upload"></i> Choose image to upload</label>
<button type="submit" name="submit" class="btn btn-primary">Create</button>
</div>
<div class="col-md-12 margin-bottom10">
<div class="row" id="image_preview">
</div>
</div>
JAVASCRIPT
var newFileList = null;
function preview_image(){
var total_file=document.getElementById("file_name").files.length;
newFileList = Array.from(event.target.files);
for(var i=0;i<total_file;i++){
$('#image_preview').append("<div class='col-md-2 margin-top10 appendedImg'><img style='width: 100%; height: 130px; object-fit: cover;' src='"+URL.createObjectURL(event.target.files[i])+"'><button class='btn btn-block btn-danger margin-top5 btnRemove' value='"+i+"'>Remove</button></div>");
}
}
$(document).on('click', '.btnRemove', function(){
$(this).closest('.appendedImg').remove();
var id = $(this).val();
newFileList.splice(id,1);
});
As what you can see from my code, I've successfully done with the removing a specific file from the list by saving to an array first then only use the splice() to delete.
So, my question is, is it possible to assign the php $_FILES array value with the newFileList array value? Since, the deletion only working on the javascript side so it doesn't affect the list from the file input of php array.
The file list of the input is read only which is how the $_FILES global is set.
See: https://developer.mozilla.org/en-US/docs/Web/API/FileList
However, you could set a hidden element that stores the files that "have been removed" and filter them in PHP on post.
Consider the following example:
When the remove button is used it adds the file name to an array which is covered to a JSON string in a hidden element.
On post, loop through the $_FILES global and if the file name is in the remove list then don't process it.
Of course you'll want to make the uploads less loose and more secure but I hope this gives you the idea.
(I haven't tested this so you may have to adjust.)
HTML
<div class="col-md-12 margin-bottom10">
<input type="file" accept="image/*" name="file_name[]" id="file_name" class="inputfile" multiple />
<label class="btn btn-danger" for="file_name"><i class="fa fa-upload"></i> Choose image to upload</label>
<button type="submit" name="submit" class="btn btn-primary">Create</button>
</div>
<div class="col-md-12 margin-bottom10">
<div class="row" id="image_preview">
</div>
</div>
<input type="hidden" id="removed_files" name="removed_files" value="" />
JavaScript
window.newFileList = [];
$(document).on('click', '.btnRemove', function () {
var remove_element = $(this);
var id = remove_element.val();
remove_element.closest('.appendedImg').remove();
var input = document.getElementById('file_name');
var files = input.files;
if (files.length) {
if (typeof files[id] !== 'undefined') {
window.newFileList.push(files[id].name)
}
}
document.getElementById('removed_files').value = JSON.stringify(window.newFileList);
});
$(document).on('change', '#file_name', function (event) {
var total_file = document.getElementById("file_name").files.length;
for (var i = 0; i < total_file; i++) {
$('#image_preview').append("<div class='col-md-2 margin-top10 appendedImg'><img style='width: 100%; height: 130px; object-fit: cover;' src='" + URL.createObjectURL(event.target.files[i]) + "'><button class='btn btn-block btn-danger margin-top5 btnRemove' value='" + i + "'>Remove</button></div>");
}
});
PHP
<?php
$removedImages = json_decode($_POST['removed_files'], true);
foreach ($_FILES['file_name'] as $FILE) {
if (in_array($FILE['name'], $removedImages)) {
continue;
}
// [import file stuff]
}

How to send cropped image with form post

How can I handle cropped image and send with post? I am using Cropper.js library. The HTML codes already in a form element. These codes copied from sample admin template. Cropping works but I cant send files.
HTML:
<div class="row">
<div class="col-md-6">
<div class="image-crop">
<img src="{{ asset('backend/images/image-upload.png') }}">
</div>
</div>
<div class="col-md-6">
<h4>Preview image</h4>
<div class="img-preview img-preview-sm" style="width: 180px;height:180px;"></div>
<hr>
<div class="btn-group">
<button class="btn btn-white" id="zoomIn" type="button">Zoom In</button>
<button class="btn btn-white" id="zoomOut" type="button">Zoom Out</button>
<button class="btn btn-white" id="rotateLeft" type="button">Rotate Left</button>
<button class="btn btn-white" id="rotateRight" type="button">Rotate Right</button>
</div>
<hr>
<div class="btn-group">
<label title="Upload image file" for="inputImage" class="btn btn-primary">
<input type="file" accept="image/*" name="file" id="inputImage" class="hide">
Upload new image
</label>
<label title="Donload image" id="download" class="btn btn-primary">Download</label>
</div>
</div>
JS:
var $image = $(".image-crop > img")
$($image).cropper({
aspectRatio: 1,
preview: ".img-preview",
done: function(data) {
// Output the result data for cropping image.
}
});
var $inputImage = $("#inputImage");
if (window.FileReader) {
$inputImage.change(function() {
var fileReader = new FileReader(),
files = this.files,
file;
if (!files.length) {
return;
}
file = files[0];
if (/^image\/\w+$/.test(file.type)) {
fileReader.readAsDataURL(file);
fileReader.onload = function () {
$inputImage.val("");
$image.cropper("reset", true).cropper("replace", this.result);
};
} else {
alert("Please upload a image file");
}
});
} else {
$inputImage.addClass("hide");
}
//Disabled Cropped Image Download
/*
$("#download").click(function() {
window.open($image.cropper("getDataURL"));
});
*/
PHP:
var_dump($_FILES);
Post Output:
you do it as a canvas first and get the base64 string toDataURL("image/png") then catch it in your server side and convert it to image again using the base64 string
kindly take a look at this post.
Convert an image into binary data in javascript

Categories

Resources