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

使用Ajax验证提交

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:

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

</script> 

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    

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });

        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:


<?php
error_reporting(E_ALL);
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"];

if($_SERVER["REQUEST_METHOD"] == "POST")
 {

     //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);
 }
 elseif($image_type=='image/gif')
 {
  $src = imagecreatefromgif($uploadedfile);
 }
 elseif($image_type=='image/jpeg' || $image_type=='image/jpg' || $image_type == 'image/pjpeg')
 {
  $src = imagecreatefromjpeg($uploadedfile);
 }else{
     //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".
 list($origWidth,$origHeight)=getimagesize($uploadedfile);

    $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
    $image_p=imagecreatetruecolor($new_width,$new_height);

 // 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
    imagecopyresampled($image_p,$src,0,0,0,0,$new_width,$new_height,$origWidth,$origHeight);

 //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;
     $stmt->execute();

     */

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

    }else{
        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条回答 默认 最新

  • 游.程 2019-06-20 01:00
    关注

    In order to solve your problem(s):

    1. You should add success property in your ajax code so that message will only be displayed when the data is processed successfully with no errors. You can apply this by replacing your code with this:
    <script> 
                // wait for the DOM to be loaded 
                $(document).ready(function() { 
                    // bind 'myForm' and provide a simple callback function 
                    $('#form1').ajaxForm({
                       success: function(response){ alert(response); }
                    }); 
                }); 
    
    </script> 
    

    So after adding the script above, you need to modify your back-end to return a response. So in your PHP code, you should modify your code and replace echo with return so that the response will be returned to the front-end, then you can alert the response

    1. I think you should ensure from the front-end (HTML) that only images with the extensions you want can be selected which i think will make it verification a lot more easier for you. You can apply this by appending an accept attribute to the input element (i.e. the one you used for selecting the images).

    Example: <input accept="image/jpeg,image/jpg,image/png">

    The code above will ensure that users can only select/upload files with the following extensions (jpg, jpeg, & png).

    1. If you want to use JavaScript to verify if the file selected is an image, then i think you should replace your readURL function with this:
    function readURL(input) {
            if (input.files && input.files[0]) {
                const fileType = input.files[0]['type'];
                const imageTypes = ['image/jpeg', 'image/jpg', 'image/png'];
                if(imageTypes.includes(fileType)) {
                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    
    
                reader.readAsDataURL(input.files[0]);
              } else { alert("Please select a valid image"); }
            }
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思