ZK Upload Image and Show It - image

how to upload an image and show it on browser using button in zk. I have tried it but the uploaded image did not appear on the browser. please show me what's wrong with my code:
this is the zul file:
<?xml version="1.0" encoding="UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" ?>
<window id="win" use="simple.zkoss.project.WindowController">
<hbox>
<button id="uploadButton" label="Upload" upload="true" onUpload="win.uploadImage((UploadEvent) event)" />
<div id="image" width="100px" height="100px" />
</hbox>
</window>
and the class:
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Div;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Image;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;
public class WindowController extends Window {
private Div image;
public void uploadImage(UploadEvent event) {
Media media = event.getMedia();
if (media instanceof org.zkoss.image.Image) {
Image im = new Image();
im.setContent((org.zkoss.image.Image) media);
im.setParent(image);
} else {
Messagebox.show(media + " is not an image", "Error", Messagebox.OK, Messagebox.ERROR);
}
}
}
the image just did not appear in 'div' tag, but when I choose another type of file (not an image) it shows the messagebox which means that the condition was right. thank you

The Div image is null. retrieve it with getFellow("image").

you need to add annotation above the onUpload method #Listen("onUpload=#uploadButton")

change the yor div by:
<image id="idBtn"/>
and your method:
public void onUpload$idBtn(UploadEvent event) {
Media media = event.getMedia();
if (media instanceof org.zkoss.image.Image) {
img_identificacion.setContent((org.zkoss.image.Image) media);
}
}

Related

Can't render image from state in React/JSX

I'm getting the path to an image from my database. The image file is stored locally. I store the path as State for the component thus keeping the component dynamic as opposed to simply importing the path form it's location. So...
this works...
render() {
return (
<div>
<Col xs={6} md={4}>
<Image src={require('../../../../public/uploads/file-1516414373384.png')}responsive />
</Col>
</div>
)
However, this does not...
class Reports extends Component {
constructor(props) {
super(props);
this.state = {
reports: [],
photos: null
}
}
componentWillMount() {
var reports = []
axios.get('/uploadUserImage')
.then( (response) => {
response.data.forEach(function(report){
reports.push(report)
})
}).then(() => {
this.setState({reports})
}).then(() => {
var path = '../../../../'+this.state.reports[0].file;
var rightPath = path.replace(/\\/g,"/");
this.setState({photos: rightPath})
})
.catch( (error) => {
console.log(error);
});
}
render() {
return (
<div>
<Col xs={6} md={4}>
<Image src={require(this.state.photos)}responsive />
</Col>
</div>
)
Even though the second non-working code compiles to the same this as the first working bit of code.
I get an error that says
Uncaught Error: Cannot find module "."
So maybe there is something wrong in my web-pack? but if that were true wouldn't both cases throw the error???
I also tried template literals...
<Image src={require(`${this.state.photos}`)}responsive />
As was the answer to a similar question, but no dice - Same error.
I think, this is because first time it trying to import image of path null (initial value of the path in state), only after getting successful response from server, it will have the correct image path.
One possible solution is, render the image only when you have a valid path means after getting response, Use conditional rendering and put the check.
Like this:
{this.state.photos ? <Image src={require(this.state.photos)} responsive /> : null}
It’s OP. I tried everything suggested here and in other similar questions. Nothing worked. I installed react-image and now everything works fine.
Wish I could give an explanation as to what’s going on under the hood, and what exactly went wrong before, but I don’t really know. Images do render now via component state. So, victory I guess.
I was running into a similar issue and found this to work in my project:
import React, { Component } from 'react';
class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
file: null
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = e => {
this.setState({
file: URL.createObjectURL(e.target.files[0])
});
};
render() {
const fileAttached = this.state.file;
return (
<div>
<input type="file" onChange={this.handleChange} />
{fileAttached ? (
<img
src={this.state.file}
alt="File Uploaded"
height="300"
width="400"
/>
) : (
<img src="" alt="No file uploaded" />
)}
</div>
);
}
}
export default ImageUpload;

Error: cannot find name ionViewDidLeave

I'm not sure where I'm going wrong with ionViewDidLeave. I'm getting an error from the terminal that says "cannot find name ionViewDidLeave". Is there something I have to import to use it? I have already imported the navController.
Here is my
ts.file
import { Component } from '#angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { EditPost } from '../edit-post/edit-post';
import { LoadingController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class Home {
buttonColor: string = '#787083';
constructor (public navCtrl: NavController, public modalCtrl: ModalController, public loading: LoadingController) {
//OTHER FUNCTIONS
/*Navigate to edit page */
editPost(){
this.buttonColor = '#553481'; //change button background color on click
this.navCtrl.push(EditPost, {})
.catch(() => {
// Page requires authentication, re-direct to Login page
this.navCtrl.setRoot(Login, {routeToPage: 'EditPost'});
});
ionViewDidLeave(){
this.buttonColor = '#787083';
};
}// end of editPost()
}//close class
HTML
<ion-footer class="footer">
<ion-segment small class="footer">
<ion-segment-button id="post" value="post" (click)="postEvent()" [ngStyle]="{'background-color': buttonColor}" small> <span class="footer">NEW POST</span></ion-segment-button>
<ion-segment-button id="edit" value="edit" (click)="editPost()" [ngStyle]="{'background-color': buttonColor}" small> <span class="footer">Edit Post</span></ion-segment-button >
</ion-segment>
</ion-footer>
When you write inside an method
ionViewDidLeave()
you are calling a function from the current scope (editPost) function. The right way to call from the object would be:
this.ionViewDidLeave()
but I guess it's not right to call it (ionViewDidLeave is part of Ionic's page lifecycle), and I guess too that what you want to do is define this method and you have a type in your code. The right code should be:
export class Home {
buttonColor: string = '#787083';
constructor (public navCtrl: NavController, public modalCtrl: ModalController, public loading: LoadingController) {
editPost(){
this.buttonColor = '#553481'; //change button background color on click
this.navCtrl.push(EditPost, {})
.catch(() => {
// Page requires authentication, re-direct to Login page
this.navCtrl.setRoot(Login, {routeToPage: 'EditPost'});
});
}// end of editPost()
ionViewDidLeave(){
this.buttonColor = '#787083';
};
}//close class

BASE64 to image angular 2

I'm trying to show an image get from a remote server with angular 2.
In my component I have an object that is an "university_info" object that is my model.
export class myClass
{
university_info : university_info;
}
myFunction()
{
this.university_info = new university_info(responseFromServer[image])
}
export class university_info
{
imageBase64 : string
constructor(image : string)
{
this.imageBase64 = image
}
}
All is working fine. I get base64 image but when I try to show it in HTML in this way :
<img [src]="'data:image/jpg;base64,'+university_info.imageBase64" />
That's is what I get :
I feel like this thread lacks concrete examples which made me have some difficulties:
Import DomSanitizer:
import { DomSanitizer } from '#angular/platform-browser';
define in constructor:
constructor(private _sanitizer: DomSanitizer) { }
Sanitize the Base64 string you want to pass as your image source (use trustResourceUrl):
this.imagePath = this._sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,'
+ toReturnImage.base64string);
Bind to html:
<img [src]="imagePath">
Solution: Just use 'data:image/jpg;base64' into your image tag like this
<img src="{{'data:image/jpg;base64,' + imagePath}}" />
You can try to use _sanitizer.bypassSecurityTrustUrl to tell angular src value is safe. Take a look at this class from angular:
class DomSanitizationService {
sanitize(context: SecurityContext, value: any) : string
bypassSecurityTrustHtml(value: string) : SafeHtml
bypassSecurityTrustStyle(value: string) : SafeStyle
bypassSecurityTrustScript(value: string) : SafeScript
bypassSecurityTrustUrl(value: string) : SafeUrl
bypassSecurityTrustResourceUrl(value: string) : SafeResourceUrl
}
and be low an example for safe html:
export class AppComponent {
private _htmlProperty: string = '<input type="text" name="name">';
public get htmlProperty() : SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(this._htmlProperty);
}
constructor(private _sanitizer: DomSanitizationService){}
}
Please find enclosed a proper example of how to upload an image in Base64 in Angular 2/4 and also its display. the actual base64 string is dumped into the debugger console and of course can be stored in database etc.
import { Component, OnInit } from '#angular/core';
// Base 64 IMage display issues with unsafe image
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'app-test',
template: `
<h1>Test 001 </h1>
<div class="form-group">
<label>Image</label>
<input type="file" class="form-control" accept="application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*" (change)="changeListener($event)">
</div>
<img *ngIf="base64Image" [src]="domSanitizer.bypassSecurityTrustUrl(base64Image)" />
`,
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
private base64Image: string;
constructor(private domSanitizer: DomSanitizer) { }
ngOnInit() {
}
changeListener($event): void {
this.readThis($event.target);
}
readThis(inputValue: any): void {
var file: File = inputValue.files[0];
var myReader: FileReader = new FileReader();
myReader.onloadend = (e) => {
this.base64Image = myReader.result;
console.log(this.base64Image);
}
myReader.readAsDataURL(file);
}
}
You have to make sure that university_info.imageBase64 is a string type then you code will work.
DEMO : http://plnkr.co/edit/pI35tx9gXZFO1sXj9Obm?p=preview
import {Component,ViewChild,Renderer,ElementRef,ContentChildren} from '#angular/core';
#Component({
selector: 'my-app',
template: `
<img [src]="'data:image/jpg;base64,'+imagePath"/>
`
})
export class App {
imagePath:string="iVBORw0KG...";
}
I would like to propose an alternative solution that builds on the one provided by #gatapia.
The proposed solution is to use the #ViewChild decorator tag (see docs here https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html), to retrieve the element reference within the component, and set the value directly as illustrated in the code snippet below. Important to note that the element being referenced via the ViewChild should be bound with to a local variable using the #, as illustrated in the code snipped below.
Also as the ElementRef docs explains, using the ElementRef directly still exposes risk of XSS also present when using DomSanitizer.
#Component({
template: `
<div>
<img #imgRef> // Note that the #imgRef reference is required to be identified by Angular
</div>
`,
})
export class MyComponent implements OnInit {
src:string;
#ViewChild('imgRef') img:ElementRef;
constructor() {
// In your case, this will be resolved from the server
this.src = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=';
}
ngOnInit() {
// Sets the value of the element
this.img.nativeElement.src = this.src;
}
}
The following plunkr provides a working code snippet of the above https://plnkr.co/edit/JXf25Pv8LqrFLhrw2Eum?p=preview
This question gets high google ranking so I thought I'd put my findings here. Using data binding to set the [src] property of an image can be problematic especially on some older mobile devices. So if you have performance issues with the sanitizer+binding approach you will have to set the src property using the DOM directly:
constructor(private el: ElementRef) {}
...
public imageChanged(base64: string) {
const im: HTMLImageElement = this.el.nativeElement.querySelector('#imgid');
im.src = data;
}
This may be ugly but its lightning fast.

Can't change the label on an excel ribbon

I've got a problem trying to set a custom label on teh fly with a ribbon using Excel-DNA.
If I don't included the annotation "getLabel='GetLabel'" then the plugin loads fine. ie the ribbon tab is shown with 2 buttons andthe button callbacks work fine.
If I do inclue the property "getLabel='GetLabel'" then the plugin doesn't even load, ie onLoad isn't called and the ribbon tab doesn't show up in excel.
Can anyone see what I'm doing wrong here. I don't see any errors when running in the debugger.
Here is my DNA file. I've tried to base it off one of the samples so it's easier to follow.
<DnaLibrary Name="Emsx Addin" RuntimeVersion="v2.0">
<ExternalLibrary Path="EmsxExcelTech1.dll" />
<Reference AssemblyPath="System.Windows.Forms.dll" />
<!-- Some images that can be used in the Ribbon ui -->
<Image Name="M" Path="M.png" Pack="true" />
<CustomUI>
<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' loadImage='LoadImage' onLoad='OnLoad'>
<ribbon>
<tabs>
<tab id='CustomTab' label='K2 Emsx' insertAfterMso='View'>
<group id='SampleGroup' label='Global Sheet Status'>
<button id='LoginCmd' label='Logon' image='M' onAction='OnLogonPressed' getLabel='GetLabel' />
<button id='BetaCmd' label='Use Beta Route' image='M' size='normal' onAction='RunTagMacro' tag='OnUseBetaRoutes' />
</group >
</tab>
</tabs>
</ribbon>
</customUI>
</CustomUI>
</DnaLibrary>
Here is my Ribbon derived C# file.
[ComVisible(true)]
public class EmsxRibbon : ExcelRibbon
{
private IRibbonUI ribbon = null;
public void OnLogonPressed(IRibbonControl control)
{
EmsxIntegration.Instance.Login();
MessageBox.Show("Hello from control " + control.Id);
if (ribbon != null)
{
ribbon.InvalidateControl(control.Id);
}
}
string GetLabel(IRibbonControl control)
{
if (control.Tag == "Logon")
{
return "Logon";
}
else
{
return "Logoff";
}
}
public static void OnUseBetaRoutes()
{
MessageBox.Show("Hello from 'ShowHelloMessage'.");
}
public void OnLoad(IRibbonUI ribbon)
{
this.ribbon = ribbon;
}
}
When you use the getLabel event, you should not use label property, so change
<button id='LoginCmd' label='Logon' image='M' onAction='OnLogonPressed' getLabel='GetLabel' />
to
<button id='LoginCmd' image='M' onAction='OnLogonPressed' getLabel='GetLabel' />
Hope this helps.

Toggle between Images asp.net MVC3

I have a place holder for a profile photo.I want it to get profile image from database (this works OK)<img src="#Url.Action("Thumbnail", "Photo", new { id = Model.Mebrief.myGuid, size = "small" })" alt="#Model.UserName" width="150" height="150"/>.
Problem:
If there is no profile image ,it should get default place holder image located here:
<img src="#Url.Content("~/Content/profile-template/img/friend_avatar_default.jpg")" alt="crazy" width="150" height="150"/>
All these are supposed to show in a div below:
<div id="profile"> </div>
NOTE: I am using .cshtml razer page.
You could try something like this in your controller.
public ActionResult Photo(int photoId)
{
MyPhoto photo = null;
try
{
MyPhoto = db.GetMyPhotoById(photoId);
return new FileStreamResult(new MemoryStream(photo.Image), photo.ImageMimeType);
}
catch (Exception ex)
{
//use the default image
return new FilePathResult(Url.Content("~/Content/profile-template/img/friend_avatar_default.jpg"), "image/jpg");
}
}
It would be helpful to see what you are doing in your controller, but I'm guessing you are returning a FileStreamResult from the bytes you get back from the database.
Hope this helps.
below is not a valid razor syntax but just an idea - Use ternary operator
if true ? new image : default image
Model != null
?
img src="#Url.Action("Thumbnail", "Photo", new { id = Model.Mebrief.myGuid, size = "small" })" alt="#Model.UserName" width="150" height="150"/>"
:
img src="#Url.Content("~/Content/profile-template/img/friend_avatar_default.jpg")" alt="crazy" width="150" height="150"/>

Resources