Preview an image before it is saved to database in Yii using Jquery - jquery-ui

I am not understanding how should I carry on to Preview an image before it is
being saved to database in yii using jquery or any method that you can suggest
view
<img id="preview_image"
src="images/<?php echo $model->pimg; ?>"
width="150px" height="120px"/>
<?php echo $form->labelEx($model,'pimg'); ?>
<?php echo $form->fileField($model, 'pimg',array('change'=>preview(this));); ?>
<?php echo $form->error($model,'pimg'); ?>
the jquery code
function preview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview_image')
.attr('src', e.target.result)
.width(100)
.height(120);
};
reader.readAsDataURL(input.files[0]);
}
}
Fatal error to function call preview().
How should I integrate this Jquery function in above form ....... $form has the htmlOptions
PLEASE HELP! I am new to Yii and am loosing my mind on this. Thank you.

This bellow code shows the image preview using jQuery
var imageTypes = ['jpeg', 'jpg', 'png']; //Validate the images to show
function showImage(src, target)
{
var fr = new FileReader();
fr.onload = function(e)
{
target.src = this.result;
};
fr.readAsDataURL(src.files[0]);
}
var uploadImage = function(obj)
{
var val = obj.value;
var lastInd = val.lastIndexOf('.');
var ext = val.slice(lastInd + 1, val.length);
if (imageTypes.indexOf(ext) !== -1)
{
var id = $(obj).data('target');
var src = obj;
var target = $(id)[0];
showImage(src, target);
}
else
{
}
}
And your HTML should be
<input type="file" name="image" onchange="uploadImage(this)" data-target="#aImgShow" />
<img id="aImgShow" src="" class="carImage" />

Related

How to upload multiple images in codigniter. Please any body shere code

How to upload multiple images in code ignite r. Please any body shear code .
this is my code to upload a file which is written in a controller.Please any body suggest what is wrong with this code.
function do_upload_slider()
{
$this->load->library('upload');
$files = $_FILES;
echo $cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload_slider();
}
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './uploads/slider/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['overwrite'] = TRUE;
return $config;
}
try this one.it may be help you
uploadform_view.php.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('imageupload/doupload');?>
<input name="userfile[]" id="userfile" type="file" multiple="" />
<input type="submit" value="upload" />
<?php echo form_close() ?>
</body>
</html>
Create A New Controller: controllers/imageupload.php
class Imageupload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('imageupload_view', array('error' => ' ' ));
}
function doupload() {
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
}
}
And that is it. Customize it to your needs, the basics are there already. And good luck!

how to use infowindow (google map API) to get back the ID of the selected location

I am displaying a list of locations (that i get through ViewBag for now) on a map and ask the user to choose one of them.
I have populated my infowindows with HTML code by looping through the list of locations.
now when the user clicks on one of the buttons in the infowindow ("Choose this one"), I want to update the view model (Venue) to include Venue.Id = the choosen location and submit back to the controller so update the database. how can I do such a thing ?
thanks a lot for your help.
here is my script code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
var rabat = new google.maps.LatLng(34.019657, -6.831833);
var mapOptions = {
zoom: 11,
center: rabat,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var list =
#Html.Raw(Json.Encode(((IEnumerable<KayenChiMVC.Models.Venue>)ViewBag.TheVenue).Select(v => new
{
venueId = v.VenueID,
venueName = v.Name,
venueDistrict = v.District,
venueType = v.SurfaceType,
venueLat = v.Latitude,
venueLon = v.Longitude
})
));
var infowindow = new google.maps.InfoWindow();
for(var i=0; i<list.length;i++){
var pos = new google.maps.LatLng(list[i].venueLat, list[i].venueLon);
var html = "<table>" +
"<tr><td>Nom:</td>" + "<td> " + list[i].venueName +" </td> </tr>" +
"<tr><td>Quartier:</td>" + "<td> " + list[i].venueDistrict +" </td> </tr>" +
"<tr><td>Type de surface:</td>" + "<td> " + list[i].venueType +" </td> </tr>" +
"<tr><td></td><td><input type='button' value='Choisir ce terrain' onclick=''/></td></tr>";
createMarker(pos, list[i].venueName, html);
function createMarker(pos,title, html){
var marker = new google.maps.Marker({
'position': pos,
'map': map,
'title': list[i].venueName
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
}
}
</script>
</section>
Add a data-id attribute to your input to hold the venue id.
<input id="myButton" type="button" data-id="123" value="Choose this one" />
and get the data-id attribute in javascript
document.getElementById('myButton').onclick = function() {
console.log(this.getAttribute('data-id')); // will log '123'
};

How to Upload files in SAPUI5?

How to upload file in SAP Netweaver server using SAPUI5? I tried to upload file using FileUploader but did not get the luck if any one can help it will be very appreciated.
Thanks in Advance
Nothing was added to the manifest nor the component nor index files. It is working for me, you just need to change the number of columns to whatever you want to fit your file.
UploadFile.view.xml
<VBox>
<sap.ui.unified:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast", "sap/m/MessageBox", "sap/ui/core/routing/History"], function(
Controller, MessageToast, MessageBox, History) {
"use strict";
return Controller.extend("cafeteria.controller.EmployeeFileUpload", {
onNavBack: function() {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("admin", true);
}
},
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
});
});
After researching a little more on this issue I finally solved this issue by myself I placed a file controller and a uploader in php which return the details related to files further, we can use it to upload it on server.
Here is the code I have used.
fileUpload.html
<!DOCTYPE html>
<html><head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<title>Hello World</title>
<script id='sap-ui-bootstrap' src='http://localhost/resources/sap-ui-core.js' data-sap-ui-theme='sap_goldreflection'
data-sap-ui-libs='sap.ui.commons'></script>
<script>
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader("myupload",{
name: "upload2",
uploadOnChange: true,
uploadUrl: "uploader.php",
uploadComplete: function (oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
alert(sResponse);
}
}});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text:'Trigger Upload',
press:function() {
// call the upload method
oFileUploader2.upload();
$("#myupload-fu_form").submit();
alert("hi");
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");
</script>
</head>
<body class='sapUiBody'>
<div id="sample2"></div>
</body>
</html>
uploader.php
<?php
print_r($_FILES);
?>
It would be good if we can see your code.
This should work.
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader({
name : "upload2",
uploadOnChange : false,
uploadUrl : "../../../upload"
});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text : 'Trigger Upload',
press : function() {
// call the upload method
oFileUploader2.upload();
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");

How to refresh an image after src change in Angular JS

I would like to selecta file and load it in angular js.
Everything work fine, the only problem the image don't refrech. I can see that everything work because when i toggle the on menu on my page with angular.js the image is been refreshing.
Here is my code :
<div ng-controller="TopMenuCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<input ng-model="photo"
onchange="angular.element(this).scope().file_changed(this)"
type="file" accept="image/*" multiple />
<output id="list"></output>
<img ng-src="{{imageSource}}">
</div>
And the Angular js script :
$scope.file_changed = function(element) {
var files = element.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, photofile; photofile = files[i]; i++) {
// var photofile = element.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
$scope.imageSource= e.target.result;
};
})(photofile);
reader.readAsDataURL(photofile);
};
}
You must call Scope.$apply when you manually update $scope.imageSource in the onLoad function, because Angular can't guess when you make this change.

loading flickr photos by a set in div jquery mobile

i am creating a jquery mobile application;this is the script to load flickr photos thumbnail in a div it is loading but it is appearing in a group thumbnail not loading each images.can load each thumbnails by editing this.i just removed my api key and my ids.
$(function() {
var api_key = 'API KEY';
var user_id = 'ID';
var photoset_id = 'PHOTO SET ID';
var large_image_size = 'Medium';
var photoset_id,photo_id;
var current = -1;
var continueNavigation = false;
var photos_service = 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos' + '&api_key=' + api_key;
var photos_url = photos_service + '&photoset_id=' + photoset_id + '&media=photos&format=json&jsoncallback=?';
var large_photo_service = 'http://api.flickr.com/services/rest/?&method=flickr.photos.getSizes' + '&api_key=' + api_key;
var $photosContainer = $('#images').find('#ba');
var $photopreview = $('#flickr_photopreview');
var $flickrOverlay = $('#flickr_overlay');
var $loadingStatus = $('.loading_small');
$(function(){
$('#images').stop().animate(200,function(){
if($photosContainer.is(':empty')){
/*
if sets not loaded, load them
*/
LoadPhotos();
}
});
},function(){
});
function LoadPhotos(){
$photosContainer.empty();
$loadingStatus.css('visibility','visible');
$.getJSON(photos_url,function(data){
if(data.stat != 'fail') {
var photo_count = data.photoset.photo.length;
var photo_count_total = photo_count ;
for(var i = 0; i < photo_count; ++i){
var photo = data.photoset.photo[i];
var photoid = photo.id;
var secret = photo.secret;
var server = photo.server;
var farm = photo.farm;
var photoUrl = 'http://farm'+farm+'.static.flickr.com/'+server+'/'+photoid+'_'+secret+'_s.jpg';
var $elem = $('<div />');
var $link = $('<a class="toLoad" href="#" />');
$link.data({
'photoid' :photoid,
'secret' :secret,
'server' :server,
'farm' :farm,
'photoUrl' :photoUrl,
'photo_title' :photo.title
});
$photosContainer.append($elem.append($link));
$link.bind('click',function(e){
var $this = $(this);
current = $this.parent().index();
photo_id = $this.data('photoid');
LoadLargePhoto();
e.preventDefault();
});
}
LoadPhotosImages();
}
});
}
function LoadPhotosImages(){
var toLoad = $('.toLoad:in-viewport').size();
if(toLoad > 0)
$loadingStatus.css('visibility','visible');
var images_loaded = 0;
$('.toLoad:in-viewport').each(function(i){
var $space = $photosContainer.find('.toLoad:first');
var $img = $('<img style="display:none;" />').load(function(){
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$photosContainer.find('img').fadeIn();
}
}).error(function(){
//TODO
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$photosContainer.find('img').fadeIn();
}
}).attr('src',$space.data('photoUrl'))
.attr('alt',$space.data('photoid'));
var $photo_title = $('<span/>',{'html':$space.data('photo_title')});
$space.append($photo_title).append($img).removeClass('toLoad');
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/jquery-latest.js"></script>
<script type="text/javascript">
function downloadImg() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
ids : "78368944#N06",
tags: "",
tagmode: "any",
format: "json",
},
function(data) {
$('.img-1').attr('src', data.items[0].media.m);
$('.tit-1').text(data.items[0].title);
$('.img-2').attr('src', data.items[1].media.m);
$('.tit-2').text(data.items[1].title);
}
);
}
$(document).ready(function() {
downloadImg();
});
</script>
</head>
<body>
<div class="img-cont"><img class="img-1" /> </div>
<h3 class="tit-1"></h3>
<div class="img-cont"><img class="img-1" /> </div>
<h3 class="tit-1"></h3>
</body>
</html>

Resources