Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

DinhoPHP

Preciso acessar com javascript a função que abre a janela de seleção d

Recommended Posts

Olá!

Através do Javascript preciso acessar a função de abrir a janela de seleção de arquivos para depois fazer o upload. Pois o botão em SWF não aparece em navegadores de celulares e eu não sei nada de actionscript. Se souberem como fazer o botão em flash aparecer, eu também agradeço.

 

ActionScript:

 

/**
* Uploader class
*
* @author Fredi Machado <fredisoft at gmail dot com>
* @date 08/16/2009
**/
package
{
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.net.*;
import flash.utils.*;
public class multiUpload extends Sprite
{
private var param:Object = LoaderInfo(parent.loaderInfo).parameters;
private var counter:Number = 0;
private var files:Object; // Files to send
private var fileIDs:Dictionary; // IDs of each file
private var fileRef:FileReference; // Reference of single file
private var fileRefList:FileReferenceList; // Multi select file references
private var vars:URLVariables; // Vars to send to the upload script
private var active:String = "";
// Events that can be listened by Javascript
static public const MOUSE_CLICK:String = "onMouseClick"; // When clicking the flash button
static public const SELECTION_CANCEL:String = "onSelectionCancel"; // When the selection window is closed/canceled
static public const FILES_SELECT:String = "onSelected"; // When the user makes a selection
static public const UPLOAD_START:String = "onStart"; // When a file upload is started
static public const UPLOAD_ERROR:String = "onError"; // When any error occurs
static public const UPLOAD_PROGRESS:String = "onProgress"; // Occurs on any progress change
static public const UPLOAD_CANCEL:String = "onCancel"; // When a upload is canceled
static public const UPLOAD_COMPLETE:String = "onComplete"; // When the upload is completed
static public const UPLOAD_ALL_COMPLETE:String = "onAllComplete"; // When all uploads from the queue are completed
static public const UPLOAD_QUEUE_CLEAR:String = "onClearQueue"; // When the queue is cleared
public function multiUpload()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.showDefaultContextMenu = false;
files = {};
fileIDs = new Dictionary();
stage.addEventListener(MouseEvent.CLICK, btnClick);
// Register Javascript callbacks
ExternalInterface.addCallback("onMouseClick", clickOpen);
ExternalInterface.addCallback("startUpload", startUpload);
ExternalInterface.addCallback("cancelUpload", cancelUpload);
ExternalInterface.addCallback("clearUploadQueue", clearQueue);
ExternalInterface.addCallback("getFile", getFile);
ExternalInterface.addCallback("setData", setData);
if (!param.scriptData)
param.scriptData = '';
}
public function btnClick(e:MouseEvent):void
{
if (active == "")
{
// trigger the click event
triggerJS(e);
// Open the select window
select();
}
}
public function select():Boolean
{
var i:int = 0;
var type:Object;
var filter:Array = new Array();
if (param.desc != "" && param.ext != "")
{
var descriptions:Array = param.desc.split('|');
var extensions:Array = param.ext.split('|');
for (var n = 0; n < descriptions.length; n++)
filter.push(new FileFilter(descriptions[n], extensions[n]));
}
if (param.multi)
{
fileRefList = new FileReferenceList();
fileRefList.addEventListener(Event.SELECT, triggerJS);
fileRefList.addEventListener(Event.CANCEL, triggerJS);
return filter.length ? fileRefList.browse(filter) : fileRefList.browse();
}
else
{
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, triggerJS);
fileRef.addEventListener(Event.CANCEL, triggerJS);
return filter.length ? fileRef.browse(filter) : fileRef.browse();
}
}
public function startUpload(continuing:Boolean = false):void
{
var id:String;
var script:String = param.script;
var file:FileReference;
if (continuing && objSize(files) == 0)
{
triggerJS({
type: UPLOAD_ALL_COMPLETE
});
return;
}
if (active != "" || objSize(files) == 0)
return;
if (script.substr(0,1) != '/' && script.substr(0,4) != 'http')
script = param.path + script;
vars = new URLVariables();
if (param.scriptData != '')
vars.decode(unescape(param.scriptData));
var urlReq:URLRequest = new URLRequest(script);
urlReq.method = (param.method == "GET") ? URLRequestMethod.GET : URLRequestMethod.POST;
urlReq.data = vars;
id = getNextId();
file = getFileRef(id);
param.maxsize = parseInt(param.maxsize);
if (param.maxsize > 0 && file.size > param.maxsize)
triggerJS({
type: "fileSize",
target: file
});
else
{
active = id;
file.upload(urlReq);
}
}
private function getNextId():String
{
var id:String;
for (id in files)
break;
return id;
}
public function validId(id:String):Boolean
{
return id in files;
}
private function addFiles(objFiles:Object):Array
{
var ret:Array = new Array();
var i:int = 0;
if (objFiles is FileReference)
ret.push(objFiles);
else if (objFiles is FileReferenceList)
ret = objFiles.fileList;
while (i < ret.length)
{
addFile(ret);
i++;
}
return ret;
}
// Adiciona a referência do arquivo
private function addFile(file:FileReference):String
{
var id:String = String(++counter);
files[id] = file;
fileIDs[file] = id;
file.addEventListener(Event.OPEN, triggerJS);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, triggerJS);
file.addEventListener(ProgressEvent.PROGRESS, triggerJS);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS, triggerJS);
file.addEventListener(IOErrorEvent.IO_ERROR, triggerJS);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, triggerJS);
return id;
}
public function cancelUpload(id:String):void
{
var file:FileReference = getFileRef(id);
if (validId(id))
file.cancel();
delete files[id];
if (active == id)
{
active = "";
startUpload(true);
}
triggerJS({
type: UPLOAD_CANCEL,
target: file
});
}
function clearQueue():void
{
for (var id in files)
cancelUpload(id);
triggerJS({
type: UPLOAD_QUEUE_CLEAR
});
}
private function fileId(file:FileReference):String
{
if (file in fileIDs)
return fileIDs[file];
return null;
}
public function getFiles(arrFiles:Array):Array
{
var ret:Array = [];
var i:int = 0;
while (i < arrFiles.length)
{
ret.push(getFileObject(arrFiles));
i++;
}
return ret;
}
private function getFileObject(file:FileReference):Object
{
return {
id: fileId(file),
name: file.name,
creation: file.creationDate.getTime(),
modification: file.modificationDate.getTime(),
size: file.size,
type: file.type
};
}
public function getFile(id:String):Object
{
if (!validId(id))
return null;
return getFileObject(getFileRef(id));
}
private function getFileRef(id:String):FileReference
{
if (validId(id))
return files[id];
return null;
}
public function setData(variables:String):void
{
param.scriptData = variables;
}
private function triggerJS(e:Object):void
{
var ret:Object;
var id:String;
ret = {};
id = e.target is FileReference ? fileId(e.target) : null;
if (id)
ret.id = id;
switch (e.type)
{
case Event.SELECT:
{
var fArr:Array;
ret.type = FILES_SELECT;
fArr = addFiles(e.target);
ret.files = getFiles(fArr);
if (param.auto)
startUpload();
break;
}
case Event.CANCEL:
{
ret.type = SELECTION_CANCEL;
break;
}
case Event.OPEN:
{
ret.type = UPLOAD_START;
break;
}
case DataEvent.UPLOAD_COMPLETE_DATA:
{
ret.type = UPLOAD_COMPLETE;
ret.data = e.data.replace(/\\/g, "\\\\");
delete files[id];
active = "";
startUpload(true);
break;
}
case ProgressEvent.PROGRESS:
{
ret.type = UPLOAD_PROGRESS;
ret.bytesLoaded = e.bytesLoaded;
ret.bytesTotal = e.bytesTotal;
break;
}
case HTTPStatusEvent.HTTP_STATUS:
{
ret.type = UPLOAD_ERROR;
ret.info = e.status;
break;
}
case IOErrorEvent.IO_ERROR:
{
ret.type = UPLOAD_ERROR;
ret.info = e.text;
break;
}
case SecurityErrorEvent.SECURITY_ERROR:
{
ret.type = UPLOAD_ERROR;
ret.info = e.text;
break;
}
case "fileSize":
{
ret.type = UPLOAD_ERROR;
ret.info = "This file exceeded the maximum size allowed.";
delete files[id];
startUpload(true);
break;
}
case UPLOAD_CANCEL:
{
ret.type = UPLOAD_CANCEL;
break;
}
case UPLOAD_QUEUE_CLEAR:
{
ret.type = UPLOAD_QUEUE_CLEAR;
break;
}
case UPLOAD_ALL_COMPLETE:
{
ret.type = UPLOAD_ALL_COMPLETE;
break;
}
case MouseEvent.CLICK:
{
ret.type = MOUSE_CLICK;
break;
}
default:
{
return;
break;
}
}
ExternalInterface.call(param.id+".op."+ret.type, ret);
}
private function objSize(obj:Object):Number
{
var i:int = 0;
for (var item in obj)
i++;
return i;
}
}
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.

      Estou com uma dúvida, referente cálculo de valores em tempo real.

      Tenho uma rotina, que faz o cálculo, o problema é mostrar o resultado.

      Quero mostrar o RESULTADO assim: 0,00  ou  0.00

      Abaixo posto o código.
      jQuery('input').on('keyup',function(){ //Remover ponto e trocar a virgula por ponto var m = document.getElementById("pgRest").value; while (m.indexOf(".") >= 0) { m = m.replace(".", ""); } m = m.replace(",","."); //Remover ponto e trocar a virgula por ponto var j = document.getElementById("pgDsct").value; while (j.indexOf(".") >= 0) { j = j.replace(".", ""); } j = j.replace(",","."); m = parseFloat(jQuery('#pgRest').val() != '' ? jQuery('#pgRest').val() : 0); j = parseFloat(jQuery('#pgDsct').val() != '' ? jQuery('#pgDsct').val() : 0); //Mostra o Resultado em Tempo Real jQuery('#pgTroco').val(m - j); <<=== aqui estou errando })  
       
      Grato,
       
      Cesar
       
       
    • Por violin101
      Caro amigos, saudações.

      Tenho uma tabela escrita em JS que funciona corretamente.
       
      Minha dúvida:
      - como devo fazer para quando a Tabela HTML estiver vazia, exibir o LOGO da Empresa ?

      Abaixo posto o script:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'i' ) return;// Não é Ctrl+A, portanto interrompemos o script evt.preventDefault(); //Chama a Função Calcular Qtde X Valor Venda calcvda(); var idProdutos = document.getElementById("idProdutos").value; var descricao = document.getElementById("descricao").value; var prd_unid = document.getElementById("prd_unid").value; var estoque_atual = document.getElementById("estoque_atual").value; var qtde = document.getElementById("qtde").value; var vlrunit = document.getElementById("vlrunit").value; var vlrtotals = document.getElementById("vlrtotal").value; var vlrtotal = vlrtotals.toLocaleString('pt-br', {minimumFractionDigits: 2}); if(validarConsumo(estoque_atual)){ //Chama a Modal com Alerta. $("#modal_qtdemaior").modal(); } else { if(qtde == "" || vlrunit == "" || vlrtotal == ""){ //Chama a Modal com Alerta. $("#modal_quantidade").modal(); } else { //Monta a Tabela com os Itens html = "<tr style='font-size:13px;'>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='id_prds[]' value='"+idProdutos+"'>"+idProdutos+"</td>"; html += "<td width='47%' height='10'>"+ "<input type='hidden' name='descricao[]' value='"+descricao+"'>"+descricao+ "<input type='hidden' name='esp[]' value='"+prd_unid+"'> - ESP:"+prd_unid+ "<input type='hidden' name='estoq[]' value='"+estoque_atual+"'></td>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='qtde[]' value='"+qtde+"'>"+qtde+"</td>"; html += "<td width='12%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrunit[]' value='"+vlrunit+"'>"+vlrunit+"</td>"; html += "<td width='14%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrtotal[]' value='"+vlrtotal+"'>"+vlrtotal+"</td>"; html += "<td width='12%' height='10' style='text-align:center;'>"+ "<button type='button' class='btn btn-uvas btn-remove-produto' style='margin-right:1%; padding:1px 3px; font-size:12px;' title='Remover Item da Lista'>"+ "<span class='fa fa-minus' style='font-size:12px;'></span></button></td>"; html += "</tr>"; $("#tbventas tbody").append(html); //Função para Somar os Itens do Lançamento somar(); $("#idProdutos").val(null); $("#descricao").val(null); $("#prd_unid").val(null); $("#qtde").val(null); $("#vlrunit").val(null); $("#vlrtotal").val(null); $("#idProdutos").focus(); //Se INCLUIR NOVO produto - Limpa a Forma de Pagamento $("#pgSoma").val(null); $("#pgRest").val(null); $("#pgDsct").val(null); $("#pgTroco").val(null); $("#tbpagar tbody").empty(); }//Fim do IF-qtde }//Fim do Validar Consumo });//Fim da Função btn-agregar  
      Grato,

      Cesar
       
    • Por violin101
      Caros amigos, saudações.

      Estou com uma pequena dúvida se é possível ser realizado.

      Preciso passar 2 IDs para o Sistema executar a função, estou utilizando desta forma e gostaria de saber como faço via JS para passar os parâmetro que preciso.

      Observação:
      Dentro da TABELA utilizei 2 Forms, para passar os IDS que preciso, funcionou conforme código abaixo.
      <div class="card-body"> <table id="tab_clie" class="table table-bordered table-hover"> <thead> <tr> <th style="text-align:center; width:10%;">Pedido Nº</th> <th style="text-align:center; width:10%;">Data Pedido</th> <th style="text-align:center; width:32%;">Fornecedor</th> <th style="text-align:center; width:10%;">Status</th> <th style="text-align:center; width:5%;">Ação</th> </tr> </thead> <tbody> <?php foreach ($results as $r) { $dta_ped = date(('d/m/Y'), strtotime($r->dataPedido)); switch ($r->pd_status) { case '1': $status = '&nbsp;&nbsp;Aberto&nbsp;&nbsp;'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#000000'; //Cor: Preta break; case '2': $status = 'Atendido Total'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#086108'; //Cor: Verde break; case '3': $status = 'Atendido Parcial'; $txt = '#000000'; //Cor: Branco $cor = '#FEA118'; //Cor: Amarelo break; default: $status = 'Cancelado'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#D20101'; //Cor: Vermelho break; } echo '<tr>'; echo '<td width="10%" height="10" style="text-align:center;">'.$r->pd_numero.'</td>'; echo '<td width="10%" height="10" style="text-align:center;">'.$dta_ped.'</td>'; echo '<td width="32%" height="10" style="text-align:left;">'.$r->nome.'</td>'; echo '<td width="10%" height="10" style="text-align:left;"><span class="badge" style="color:'.$txt.'; background-color:'.$cor.'; border-color:'.$cor.'">'.$status.'</span></td>'; echo '<td width="5%" style="text-align:center;">'; ?> <div class="row"> <?php if($this->permission->checkPermission($this->session->userdata('permissao'), 'vPedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/visualizar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-warning" title="Visualizar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-search icon-white"></i></button> </form> <?php } if($this->permission->checkPermission($this->session->userdata('permissao'), 'ePedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/editar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-primary" title="Editar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-edit icon-white"></i></button> </form> <?php } ?> </div> <?php echo '</td>'; echo '</tr>'; } ?> </tbody> </table> </div>
      Grato,

      Cesar.
    • Por belann
      Olá!
       
      Estou usando o editor quill em uma página html, sem fazer a instalação com npm, mas usando as api´s via internet com http, no entanto não consigo fazer a tecla enter funcionar para mudança de linha, tentei essa configuração abaixo, mas não funcionou.
       
      modules: {       syntax: true,       toolbar: '#toolbar-container',       keyboard: {         bindings: {           enter: {             key: 13,             handler: function(range, context) {                       quill.formatLine(range.index, range.length, { 'align': '' });             }           }  
       
    • Por violin101
      Caros amigos, saudações.
       
      Gostaria de poder tirar uma dúvida com os amigos.
       
      Como faço uma função para Comparar a Data Digitada pelo o Usuário com a Data Atual ?

      Data Digitada:  01/09/2024
       
      Exemplo:
      25/09/2024 é menor que DATA Atual  ====> mensagem: informe uma data válida.
      25/09/2024 é igual DATA Atual ===> o sistema libera os INPUT's.
       
      Como faço uma comparação com a Data Atual, para não Deixar Gravar Data retroativa a data Atual.
       
      Grato,
       
      Cesar
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.