Jump to content

Recommended Posts

Posted (edited)

Bom dia,

Estou a tentar fazer upload de imagens para uma pasta sem fazer refresh à página, para isso estou a usar javascript e ajax. Mas estou com uns erros..

Isto é a função que recebe o valor do fileup e manda o o ficheiro update.php .

function update() {
var fileup = document.getElementById("fileup").value;
//alert(fileup);

$.post('update.php', { fileup: fileup  }, function(resposta) {
  $(".loader").slideDown();
  if (resposta != false) {
// Exibe o erro na div
alert(resposta);
$(".loader").html(resposta);
  }
  else {
$(".loader").html("Alteração concluída com sucesso!");
  }
});
}

O ficheiro update.php é este:

// Recuperamos os valores dos campos através do método POST
$_FILES['fileup']['name'] = $_POST["fileup"];
$uploadpath = '../arquivo/original/';	  // directory to store the uploaded files
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png');		// allowed extensions
if($_FILES['fileup']['name']!=""){
 $uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);	   // gets the file name
 $sepext = explode('.', strtolower($_FILES['fileup']['name']));
 $type = end($sepext);	   // gets extension
 list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);	 // gets image width and height
 $err = '';		 // to store the errors
}
$alwidth = 300;			// maximum allowed width, in pixels
$alheight = 300;  
if(isset($width) && isset($height) && ($width <= $alwidth || $height <= $alheight)) {
$err .= '<br/>O tamanho mínimo da imagem deve ser: '. $alwidth. ' x '. $alheight; }
if($err == '') {
//echo "erros".$err;
$fileName = $_FILES["fileup"]["name"];
$fileTmpLoc = $_FILES["fileup"]["tmp_name"];
$pathAndName = '../arquivo/original/'.$_POST["artigo"].'.'.$type.'';
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);

}

Está-me a dar o seguinte erro: Warning: getimagesize() [function.getimagesize]: Filename cannot be empty inC:\xampp\htdocs\WebApps\ws_apps\ws_app3\article-details\update.php on line 45

A linha 45 é esta: list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);

O que tenho que mandar no valor de $_FILES['fileup']['tmp_name'] ?

Edited by NunoDinis

Estranha forma de vida que tem a capacidade de transformar comandos em mensagens de erro.

ndsotware.org

Posted (edited)

Eu não sei como é que se faz com o jQuery, mas sei como se faz com o API do browser.

Os browsers que suportam (leitura e) o envio de ficheiros suportam:

https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData

Basta fazeres add do input com o(s) ficheiro(s)

var request = new XMLHttpRequest();
// ...
var formData = new formData();
formData.append('file', fileup.files[0]);
//...
request.send(formData);

Para fazer isto usando jQuery... Não faço ideia. Tens aqui as ferramentas que precisas para fazê-lo usando o API do browser, pode ser que descubras.

EDIT: Tinha um erro no js. Agora já deve estar bem.

Edited by brunoais

"[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31

Life is a genetically transmitted disease, induced by sex, with death rate of 100%.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.