【问题标题】:Uploading images using php, but without page refresh使用php上传图片,但没有页面刷新
【发布时间】:2014-03-29 01:59:51
【问题描述】:

所以一般来说,我没有问题(还),但我需要建议。我不想制作一个用户可以上传他/她的图片的页面。但是上传不应该刷新页面,因为用户输入的其他数据会丢失。我知道有一堆 ajax 和 php 上传帖子,但事情就是这样。旧版浏览器不支持使用 XMLHttpRequest 2。我希望至少支持 IE9。我也知道有一个 iframe 解决方案。但在我看来,今天使用 iframe 就像在车库里有一辆新宝马时驾驶 Mr.Beans Mini 一样(无意冒犯)。那么有人可以给我建议我该怎么做吗?我应该走哪条路?

谢谢

【问题讨论】:

  • 据我所知,ajax upload 没有真正的解决方案。我见过的所有代码都是iframes的替代品,所以恐怕你需要这样做......
  • 我在控制面板中多次使用swf_upload 插件。它的工作原理很清楚。我知道这些天不接受闪存技术。但是没有更多的选择。据我所知,您可以使用 iframe 或 flash 技术。
  • @Madurai Citizen 我访问了该页面,发现“当前文件上传仅在 Firefox 和 Chrome 中有效”。我需要它至少在 IE9 中工作
  • Uploadify 可能适合您的需求。 uploadify.com

标签: php ajax xmlhttprequest internet-explorer-9 image-uploading


【解决方案1】:

这不是最好的方法,事实上我正在寻找一种更快的方法来做到这一点,但这是我自己编写的代码,可以将图像数据上传到数据库并自动更改您的个人资料照片无需刷新。

首先是客户端的 HTML、CSS 和 Javascript/JQuery。

//NOTE: this code is jquery, go to JQuery.com and find the download then link it in a script tag

$("#activateFile").on('click', function(){
   $("#fileBrowser").click();
  });

//if you want a finish edit button then use this otherwise put this code in the fileBrowser change event handler below KEEP THE readURL(this) OR IT WON'T WORK!

$("#finishEdit").on('click', function(){
  
    var imgData = document.getElementById('image').src;
  
   //imageData is the variable you use $_POST to get the data in php
   $.post('phpscriptname.php', {imageData:imgData}, function(data){ 
     
        //recieve information back from php through the echo function(not required)
     
     });
  });


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

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
	reader.onload = function (e) {
	  $('#image').attr('src', e.target.result)
    };
	  		
  reader.readAsDataURL(input.files[0]);
  }
}
#fileBrowser{
  display: none;
  }

#image{
  width: 200px;
  height: 200px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title>Whatever your title is</title>
   </head>
  <body>
    
    <img id="image" src="somesource.png" alt="somesource"/>
    <!-- NOTE: you can use php to input the users current image in the source attribute -->
    <br/>
    <br/>
    
    <!-- position and style these however you like -->
    
    <input type="file" id="fileBrowser"> <!-- this is display none in css -->
    <button id="activateFile">Choose files</button>
    <br/>
    <br/>
    <button id="finishEdit">Done</button>
    
  </body>
</html>

现在我将展示带有数据库的服务器端

require("yourconnectiontodatabase.php"); //create a connection to your db.

$imgData = $_POST['imageData']; //the same variable we gave it in the jquery $.post method.

//The bad part now is because we are using data straight from the input I don't think it's possible to know if the content type of the file is an image. This is a security flaw as people could try upload .exe files however, I do know the imagedata we get in javascript contains the filetype it is so you could check in javascript if it's an image type like if it's png or jpeg.

//NOTE: when looking for types in images use image/type for example image/png

//upload image to database

$updateprofile = mysql_query("UPDATE table_name SET profileimage='$imgData' ");

【讨论】:

    【解决方案2】:

    创建连接文件conn.php

    <?php
    $dbhost ='localhost';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'test';
    $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die('could not connect database');
    mysql_select_db($dbname) or die('could not select database');
    ?>
    

    用 index.php 创建图片上传页面

    <?php
    include('conn.php');
    session_start();
    $session_id='1'; 
    ?>
    <html>
    <head>
    </head>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
    
    <script type="text/javascript" >
        $(document).ready(function() { 
            $('#photoimg').on('change', function() { 
                $("#preview").html('');
                $("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
                $("#imageform").ajaxForm({
                    target: '#preview'
                }).submit();
            });
        }); 
    </script>
    
    <style>
    
    body
    {
    font-family:arial;
    }
    .preview
    {
    width:200px;
    border:solid 1px #dedede;
    padding:10px;
    }
    #preview
    {
    color:#cc0000;
    font-size:12px
    }
    
    </style>
    <body>
    <div style="width:600px">
    
    <form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
    Upload your image <input type="file" name="photoimg" id="photoimg" />
    </form>
    <div id='preview'>
    </div>
    
    
    </div>
    </body>
    </html>
    

    创建图片上传php脚本ajaxupload.php

    <?php
    include('conn.php');
    session_start();
    $session_id='1';
    $path = "uploads/";
    
    $valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
    try {
            if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
                if($_FILES) {
                    $name = $_FILES['photoimg']['name'];
                    $size = $_FILES['photoimg']['size'];
                    if(strlen($name)) {
                        list($txt, $ext) = explode(".", $name);
                        if(in_array($ext,$valid_formats)) {
                            if($size<(1024*1024)) {
                                $actual_image_name = time().$session_id.".".$ext;
                                $tmp = $_FILES['photoimg']['tmp_name'];
                                if(move_uploaded_file($tmp, $path.$actual_image_name))
                                {
                                    mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
                                    echo "<img src='uploads/".$actual_image_name."' class='preview'>";
                                } else {
                                    throw new Exception("fiald to upload image");
                                }
                            } else {
                                throw new Exception("Image file size max 1 MB");
                            }
                        } else {
                            throw new Exception("Invalid file format..");
                        }
                    } else {
                     throw new Exception("Please select image..!");
                    }
                } else {
                 throw new Exception("Please select image..!");
                }
            } 
        } catch(Exception $e) {
            echo $e->getMessage();
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 2011-08-28
      • 2014-12-04
      • 2019-03-07
      • 2012-02-11
      相关资源
      最近更新 更多