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

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!

Related

Page directs only once on mvc

I'm trying to direct to a page on my project from the Index (project homepage).
It worked only once.
This code is from the parkingLotscontroller
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
var totalQuery =
(from lot in db.parkingLots
orderby lot.PricePerHour
select new
{
ID = lot.parkingLotID,
address = lot.addressParkingLot,
latitude = lot.latitudeParkingLot,
longtitude = lot.longtitudeParkingLot,
Status = lot.statusParkingLot,
PricePerHour = lot.PricePerHour
})
.Union(from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select new
{
ID = pub.publicParkingID,
address = pub.addressPublicParking,
latitude = pub.latitude,
longtitude = pub.longtitude,
Status = pub.statusParking,
PricePerHour = pub.PricePerHourpublicParking
});
var data2 = totalQuery.ToList();
var jsonString2 = JsonConvert.SerializeObject(data2);
if (jsonString2 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJson.json"), jsonString2);
db.SaveChanges();
return View();
}
This code is from the view
#{
ViewBag.Title = "TotalPs";
}
<h2>TotalPs</h2>
<head>
<style>
#map {
height: 700px;
width: 1000px;
border: 1px solid black;
margin: 0 auto;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyApsEFrg9i2dlhq493ME30ETlDGDNbQvWI" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<br />
<br />
<div class="topnavI" align="center">
<p style="font-size:16px;"> Enter the address to search for available parking spaces</p>
<input type="text" placeholder="Search for address" size="40">
</div>
<br />
<br />
<div id="map"></div>
<script>
var map;
function initialize() {
var mapProp = {
center: new google.maps.LatLng(32.04772750000001, 34.7609645),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
};
$(document).ready(function () {
var url = "../../Content/TotalJson.json";
initialize();
$.getJSON(url, function (data) {
$.each(data, function (i, field) {
$('#list').append("<li>" + data[i].latitude + " & " + data[i].longtitude + "</li>");
createMarker(data);
function createMarker(data) {
var marker = new google.maps.Marker({
icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png',
position: new google.maps.LatLng(data[i].latitude, data[i].longtitude),
map: map,
title: field.crossroad
});
};
});
});
});
</script>
<body>
</body>
And the Index page
#Html.ActionLink("INBAL", "TotalPs", "parkingLots")
So on server side it works perfectly and the view immediatly comes up,
but on cliet side it takes a while to load and then
throws an error.
What is the problem and how do I fix it?
Thanks!
Just make a controller action that returns the JSON and call it from the client instead of writing to a file. If multiple users hit your application, multiple processes are going to attempt to write to the same file and error out.
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
return View();
}
public JsonResult TotalPData()
{
var totalQuery =
(from lot in db.parkingLots
orderby lot.PricePerHour
select new
{
ID = lot.parkingLotID,
address = lot.addressParkingLot,
latitude = lot.latitudeParkingLot,
longtitude = lot.longtitudeParkingLot,
Status = lot.statusParkingLot,
PricePerHour = lot.PricePerHour
})
.Union(from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select new
{
ID = pub.publicParkingID,
address = pub.addressPublicParking,
latitude = pub.latitude,
longtitude = pub.longtitude,
Status = pub.statusParking,
PricePerHour = pub.PricePerHourpublicParking
});
return Json(totalQuery);
}
and then
$(document).ready(function () {
var url = "#Url.Action("TotalPData", "ParkingLots")";
I have no idea why you are calling db.SaveChanges() since you are only reading data and not updating anything.

Embedded Facebook post does not shows properly in UIWebView

I'm trying to show facebook embedded post inUIWebView.
I get sample code from facebook developer portal and load it into UIWebView.
And see only blank screen.
Then I put this code in local html file and opened it in Chrome. Still nothing, but i see that embed appeared in half second and then vanished.
I try many different embedded html examples with same result.
Here is my code:
<html>
<body>
<div id="fb-root"></div>
<script>(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/ru_RU/sdk.js#xfbml=1&version=v2.3&appId=334367389999440";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-post" data-href="https://www.facebook.com/FacebookDevelopers/posts/10151471074398553" data-width="500">
<div class="fb-xfbml-parse-ignore">
<blockquote cite="https://www.facebook.com/FacebookDevelopers/posts/10151471074398553"><p>Be the first to know
when we release a new video by subscribing to our official Facebook Developers YouTube channel!
http://www.youtube.com/facebookdevelopers</p>Posted by Facebook Developers on 29 Май 2013 г.
</blockquote>
</div>
</div>
</body>
</html>
I don't find any reason of adding script in the HTML, as you said you have found sample code in FB docs.
Below code is working fine:-
<html>
<body>
<div id="fb-root"></div>
<div class="fb-post" data-href="https://www.facebook.com/FacebookDevelopers/posts/10151471074398553" data-width="500">
<div class="fb-xfbml-parse-ignore">
<blockquote cite="https://www.facebook.com/FacebookDevelopers/posts/10151471074398553"><p>Be the first to know
when we release a new video by subscribing to our official Facebook Developers YouTube channel!
http://www.youtube.com/facebookdevelopers</p>Posted by Facebook Developers on 29 Май 2013 г.
</blockquote>
</div>
</div>
</body>
</html>
The only way to resolve the problem is create a proxy service with facebook-embed. Before insert your HTML-code into UIWebView check it for fb-post and fb-video:
// Facebook Video Embed
if ([HTMLcontent rangeOfString:#"fb-video"].location != NSNotFound) {
[self appendFBEmbed:htmlContent type:#"video"];
}
// Facebook Post Embed
if ([HTMLcontent rangeOfString:#"fb-post"].location != NSNotFound) {
[self appendFBEmbed:htmlContent type:#"post"];
}
... // Your some code before </body></html>
[htmlContent appendString:#"</body></html>"];
[[self webView] loadHTMLString:[self HTMLcontent] baseURL:nil];
...
- (void)appendFBEmbed:(NSMutableString*)html type:(NSString* )type
{
NSString *locale = getYourCurrentLocaleIdentifier();
[html appendFormat:#"<script type=\"text/javascript\">"];
[html appendFormat:#"var items = document.getElementsByClassName('fb-%#');", type];
[html appendFormat:#"for (i=0; i<items.length;i++) {"];
[html appendFormat:#" var item = items[i];"];
[html appendFormat:#" var url = item.getAttribute(\"data-href\");"];
[html appendFormat:#" var src = 'http://YOUR-APP-HOST/facebook/emded.html?type=%#&url=' + encodeURIComponent(url) + '&locale=%#&width=%d';", type, locale, getYourCurrentDisplayWidth()];
[html appendFormat:#" item.innerHTML = '<iframe class=\"facebook fb-%#\" frameborder=\"0\" src=\"' + src + '\"></iframe>';", type];
[html appendFormat:#"}"];
[html appendFormat:#"</script>"];
}
And my remote page source code (PHP Phalcon Controller):
// FacebookController.php
<?php
class FacebookController extends \Phalcon\Mvc\Controller
{
public function indexAction()
{
$type = trim($this->request->get('type'));
if (in_array($type, ['post', 'video']) === FALSE) {
throw new \Exception('Unknown fb-post type');
}
$url = trim($this->request->get('url'));
$host = parse_url($url, \PHP_URL_HOST);
if ($host === FALSE) {
throw new \Exception('Invalid URL'); // URL is not URL
}
if ($host !== NULL /* related URL */ && $host !== 'facebook.com' && $host !== 'www.facebook.com') {
throw new \Exception('Forbidden URL'); // Not a Facebook-URL
}
$locale = trim($this->request->get('locale'));
if ($locale) {
if (strlen($locale) > 10) {
throw new \Exception('Invalid Locale'); //
}
$localesXML = new \SimpleXMLElement(ROOT_PATH . '/../data/facebook-locales.xml', NULL, TRUE); // Where ROOT_PATH . '/../data/facebook-locales.xml is a local copy of https://www.facebook.com/translations/FacebookLocales.xml
$result = $localesXML->xpath('//representation[.="' . htmlentities($locale) . '"]');
if (count($result) > 0) {
$locale = (string) $result[0];
} else {
$locale = NULL;
}
} else {
$locale = NULL;
}
if ($locale === NULL) {
$locale = "en_US";
}
$width = intval(trim($this->request->get('width')));
if ($width < 100 || $width > 3000) {
throw new \Exception('Invalid width param');
}
$viewData = [
'type' => $type,
'url' => $url,
'width' => $width,
'locale' => $locale,
];
foreach ($viewData as $k => $v) {
$this->view->setVar($k, $v);
}
}
}
<!-- /views/facebook/index.phtml -->
<html>
<body>
<div class="fb-<?= $type ?>" data-href="<?= $url ?>" data-width="<?= $width ?>"></div>
<script src="https://connect.facebook.net/<?= $locale ?>/sdk.js#xfbml=1&version=v2.3"></script>
</body>
</html>
Example (blured text is my HTML over fb-embed):

Gadget OAUTH request returns Internal Server Error

I am developing a gadget (html, JS) to run inside Google Calendar page. My OAUTH authorization
works fine but only for 1 hour. If I repeat the same request every 5 minutes, I have good results for 1 hour, and then I get "[500]Internal server error" forever. The reason is a bad token. I get a new one after 1 hour (I can see it with console.log(shindig.auth.getSecurityToken()) and on Network tab (makeRequest details, Form data, st)), but it causes "[500]Internal Server Error". The situation stays the same after 2 hours: I get new token, but it causes "[500]Internal Server Error". What am I doing wrong?
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="test_gadget">
<Require feature="opensocial-0.8" />
<Require feature="locked-domain"/>
<Require feature='auth-refresh'/>
<OAuth>
<Service name="google">
<Access url="https://www.google.com/accounts/OAuthGetAccessToken" method="GET" />
<Request url="https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/tasks" method="GET" />
<Authorization url="https://www.google.com/accounts/OAuthAuthorizeToken?oauth_callback=http://oauth.gmodules.com/gadgets/oauthcallback" />
</Service>
</OAuth>
</ModulePrefs>
<Content type="html">
<![CDATA[
<!-- shindig oauth popup handling code -->
<!-- <script src="http://gadget-doc-examples.googlecode.com/svn/trunk/opensocial-gadgets/popup.js"></script> -->
<script type="text/javascript" src="https://rawgit.com/Appiens/daybyday_gadget/master/javascript/shindig.js"></script>
<script type="text/javascript">
var requestInterval = 5 * 60 * 1000;
var timerFetch = -1;
var API_KEY = 'AIzaSyCuKllVMlv0ENk8Skg8_-IKM1Cs9GeL-NU';
function fetchData() {
var params = {};
url = "https://www.googleapis.com/tasks/v1/users/#me/lists?key=" + API_KEY;
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
params[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = "always";
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(url, OnFetchData, params);
}
function OnFetchData(response) {
var d = new Date();
var token = shindig.auth.getSecurityToken();
if (response.oauthApprovalUrl) {
var popup = shindig.oauth.popup({
destination: response.oauthApprovalUrl,
windowOptions: null,
onOpen: function() { showOneSection('waiting'); },
onClose: function() { fetchData(); }
});
var personalize = document.getElementById('personalize');
personalize.onclick = popup.createOpenerOnClick();
var approvaldone = document.getElementById('approvaldone');
approvaldone.onclick = popup.createApprovedOnClick();
showOneSection('approval');
}
else if (response.data) {
console.log(d + ' ' + token);
var taskLists = [];
taskLists = response.data.items;
for(var i=0; i< taskLists.length; i++) {
console.log(taskLists[i].title);
}
if (document.getElementById('main').style.display = 'none') {
showOneSection('main');
}
}
else {
console.log(d + ' ' + token);
console.log( JSON.stringify(response));
if (document.getElementById('main').style.display = 'none') {
showOneSection('main');
}
}
timerFetch = setTimeout(fetchData , requestInterval);
}
function showOneSection(toshow) {
var sections = [ 'main', 'approval', 'waiting'];
for (var i=0; i < sections.length; ++i) {
var s = sections[i];
var el = document.getElementById(s);
if (s === toshow) {
el.style.display = "block";
} else {
el.style.display = "none";
}
}
}
gadgets.util.registerOnLoadHandler(fetchData);
</script>
<div id="main" style="display: none;">
</div>
<div id="approval" style="display: none">
Personalize this gadget
</div>
<div id="waiting" style="display: none">
Please click
I've approved access
once you've approved access to your data.
</div>
]]>
</Content>
</Module>

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

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" />

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

Resources