weixin_33738578 2019-06-19 23:09 采纳率: 0%
浏览 45


I'm bulding a website that allows users to upload a picture and then get the EXIF info shown in a user-friendly way.

I also want to make available an option for users to be able to share their picture online.

At the moment I already have the JavaScript for the image preview fully working: I select an Image on a Form and it appears on the website...

Now, after the users load the picture into the preview area a button appears that allows the user to upload the picture.

The thing is that I want the upload to be done without the page refreshing...

I've already asked a question about it and it has been solved by using this bit of code on the "head" of my main page, where the form is:

            // wait for the DOM to be loaded 
            $(document).ready(function() { 
                // bind 'myForm' and provide a simple callback function 
                $('#form1').ajaxForm(function() { 
                    alert("Image uploaded!"); 


This does work... When I press the button to upload the picture it does get uploaded, it stays on page with the preview still on sight and an alert message is shown saying "Image uploaded"..

The problem is that, in case i choose like a ".txt" file and press to upload it will still say "Image uploaded", even though it hasn't uploaded it, because on the PHP file I'm verifying the file type before uploading it, only allowing .png and .jpg...

It will also say "image uploaded" even if I modify my PHP file on purpose with wrong info... So, basically. it's not testing anything atm...

I also had my PHP coded to show a message in this situation saying "Only jpeg and png allowed..."... But this would be shown on a blank "after submiting"-page of course, which I don't want...

The question is: As that bit of code that uses Ajax kinda "overrides" the error messages present on my PHP code, how do I modify it in order to show an error message in case it isn't an image that's trying to be uploaded?

Another way could be for me to verify if it's an image when loding it to the preview-area via JavaScript maybe?

My JavaScript code to load the image into a "preview area":

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img1').attr('src', e.target.result);

            //Mostrar a imagem e o mapa ao fazer o upload
            var x = document.getElementById("itens");
            if (window.getComputedStyle(x).display === "none") {
                x.style.display = "block";
            var y = document.getElementById("exif");
            if (window.getComputedStyle(y).display === "none") {
                y.style.display = "block";  

            y.scrollIntoView(true); //Redireciona o ecrã para a imagem carregada    



        var botao = document.getElementById("upload_img");

        var z = document.getElementById("link_foto");

        botao.onclick = function() {
            if (window.getComputedStyle(z).display === "none") {
                z.style.display = "block";

My PHP code to upload the image to a folder and database:

ini_set('display_errors', 1);

$link = mysqli_connect("localhost","root","","geopic") or die("Error ".mysqli_error($link)); //ligação à base de dados e à tabela

 // O array global PHP $_FILES permite o upload de imagens do computador para o servidor.
 $image = $_FILES["imgInp"]["name"];

 //devolve o nome da cópia temporária do ficheiro presente no servidor 
 $uploadedfile = $_FILES['imgInp']['tmp_name'];

 //Devolve o tipo de ficheiro
 $image_type =$_FILES["imgInp"]["type"];


     //imagecreatefrompng — Cria uma nova imagem a partir do ficheiro porque não se sabe se o utilizador vai fazer o upload de um ficheiro com extensão permitida 
 if($image_type=='image/png' || $image_type=='image/x-png')
  $src = imagecreatefrompng($uploadedfile);
  $src = imagecreatefromgif($uploadedfile);
 elseif($image_type=='image/jpeg' || $image_type=='image/jpg' || $image_type == 'image/pjpeg')
  $src = imagecreatefromjpeg($uploadedfile);
     //se não for uma imagem mostra a mensagem e termina o script
     exit ("Only jpeg and png allowed..." ) ; 

 //getimagesize() Esta função vai "buscar" o tamanho da imagem carregada. O tamanho original é necessário para realizar o "resize" na função"imagecopyresampled".

    $maxWidth = 1280; //Define a largura máxima da imagem a guardar no servidor
    $maxHeight = 800; //Define a altura máxima da imagem a guardar no servidor

 if ($maxWidth == 0)
        $maxWidth  = $origWidth;

    if ($maxHeight == 0)
        $maxHeight = $origHeight;

    // Calcula a rácio dos tamanhos máximos desejados e originais
    $widthRatio = $maxWidth / $origWidth;
    $heightRatio = $maxHeight / $origHeight;

    // Rácio usada para calcular novas dimensões da imagem
    $ratio = min($widthRatio, $heightRatio);

    // Calcula as novas dimensões da imagem
    $new_width  = (int)$origWidth  * $ratio;
    $new_height = (int)$origHeight * $ratio;    

 // Função que serve para a imagem não perder qualidade perante o redimensionamento

 // No caso da imagem ser PNG com fundo transparente, esta função mantém a transparência
    imagealphablending($image_p, false);
    imagesavealpha($image_p, true);
 //Função que vai redimensionar a imagem

 //Vai gerar um nome para a foto com base na hora atual, para nunca existirem fotos com o mesmo nome

 $temp = explode(".", $image);
 $newfilename = round(microtime(true)) . '.' . end($temp);

 $filepath = "http://localhost/geoPic/photos/".$newfilename;

// A função move_uploaded_file vai realizar o carregamento da foto para a pasta.  
 if(move_uploaded_file($_FILES["imgInp"]["tmp_name"], "photos/".$newfilename))
     $stmt = $link->prepare("INSERT INTO photo (name, path) VALUES (:name, :path)");
     $stmt->bindParam(':name', $nome);
     $stmt->bindParam(':path', $caminho);

// insert one row
     $nome = $newfilename;
     $caminho = $filepath;


    $query_image = "insert into photo (name, path) values ('".$newfilename."', '".$filepath."')";

    if(mysqli_query($link, $query_image)){
        //$link_foto = mysqli_query($link,"SELECT path FROM carro WHERE name = $newfilename");

        echo "Image uploaded";

        echo "image not uploaded";


Thanks in advance..

You guys are awesome and have already provided me with crucial help in this project's development!

  • 写回答

1条回答 默认 最新


      相关推荐 更多相似问题


      • ¥15 有偿找一份verilog语言的cnn代码带讲解
      • ¥15 关于#mysql#的问题:mysql 组内排名,取各组的销售金额前10
      • ¥15 有人用过颜色传感器吗?
      • ¥50 求一个SQL长料切短料的优化排版算法
      • ¥15 python 删除TXT文档中小写字母
      • ¥15 ValueError: not enough values to unpack (expected 2, got 0)
      • ¥15 js怎么禁止修改域名
      • ¥15 Cursor为什么在Windows11打不开
      • ¥30 java调用javacv遇到的问题
      • ¥15 如何使用matlab画出带宽100Khz,时长100ms信号的LFM形式的时频图啊