如何使用ajax上传图像并进行预览

时间:2012-07-26 11:16:07

标签: php jquery html ajax

我试图使用ajax将图像上传到图像文件夹,但它无法正常工作 当我选择图像时,图像应该上传到本地硬盘中的文件夹,我将进一步使用它。

请帮帮我

我的代码是:

SCRIPT     

$(document).ready(function() { 
$('#pathAbout,#path,#pathWork').change(function(){
if($(this).val() !=""){
    $.ajax({
       type: "POST",
       url: "imageLoad.php", 
       data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",
       success: function(msg){
        alert(msg);
       }
     });
}
});
}); 
</script>

HTML

<form method="POST" action="tabs.php?page=HOME" enctype="multipart/form-data">
<table>
<tr>
<td><label>Choose Image</label></td>
<td><input type="file" id ="pathAbout" name="imgPath" /></td>
</tr>

</table>
</form>

PHP

if(!empty($_POST)) {
if((isset($_POST['name']) && $_POST['name'] != '') || (isset($_POST['type']) && $_POST['type'] != '') ||(isset($_POST['tmp_name']) && $_POST['tmp_name'] != ''))
{
$name = $_POST['name'];
$type = $_POST['type'];
$tmp_name = $_POST['tmp_name'];
$extension = strtolower(substr($name, strpos($name , '.') +1));
if(($extension == 'png' || $extension == 'jpeg' || $extension == "jpg")&&($type == "image/png" || $type == "image/jpeg" || $type == "image/jpg"))
{
    $location = 'images/';
    if(move_uploaded_file($tmp_name,$location."$name"))
        {
            echo "Loaded";
        } else {
            echo "Error occured";
        }
} else {
    echo "Unsupported file format";
}
} else {
    echo "Please choose a file";
}
} else {
echo "No Information found";
}

这是我的代码,但是当我选择文件时没有发生任何事情

5 个答案:

答案 0 :(得分:2)

如果您希望在此处使用Uploadify,您还可以查看演示和示例代码,例如 -

$(function() {
$("#file_upload").uploadify({
    'formData'      : {'someKey' : 'someValue', 'someOtherKey' : 1},
    'swf'           : '/uploadify/uploadify.swf',
    'uploader'      : '/uploadify/uploadify.php',
    'onUploadStart' : function(file) {
        $("#file_upload").uploadify("settings", "someOtherKey", 2);
    }
});
});

$("#image_upload2").uploadify(uploadifyBasicSettingsObj);

uploadifyBasicSettingsObj.onUploadSuccess = function(file, data, response) 
{
    $('.tempImageContainer2').find('.uploadify-overlay').show();

    /* Here you actually show your uploaded image.In my case im showing in Div  */
    $('.tempImageContainer2').attr('style','background- image:url("../resources/temp/thumbnail/'+data+'")');
    $('#hidden_img_value2').attr('value',data);
}

HTML代码:

<div class="boxWrapper tempImageContainer2" data-image-container-id="2">
   <input type="file"  accept="gif|jpg" name="image2" style="" id="image_upload2"/>
   <input type="hidden" value="" name="image[]" id="hidden_img_value2">
   <input type="hidden" name="upload_path" value="" id="upload_path2" class="upload_path">
   <div class="uploadify-overlay">Change</div>
   <a class="remove-pic-link" href="javascript:void(0)" style="display:none">Remove</a>
 </div>

答案 1 :(得分:1)

无法使用AJAX直接上传图像,但有一些库可以创建动态iframe来实现此目的。

看看这个,我在几个项目中使用过:valums.com/ajax-upload。它甚至附带了几个PHP应用程序框架的示例服务器代码。

答案 2 :(得分:1)

您无法使用AJAX上传文件,您需要使用包含'iframe'web form以及javascript的技巧。
This link可能会对您有所帮助。

答案 3 :(得分:1)

<强> HTML

<div class="field">
    <label class="w15 left" for="txtURL">Logo:</label>
    <img id="logoPreview" width="150px" height="150px" src='default.jpg' />
    <input class="w60" type="file" name="txtURL" id="txtURL" />
</div>

<强> JQuery的

$('#txtURL').on('change', function(){

    $.ajaxFileUpload({
           type         :   "POST",
           url          :   "ajax/uploadImage",
           dataType     :   "json",
           fileElementId:   'txtURL',
           data         :   {'title':'Image Uploading'},
           success      :   function(data){

                $('#logoPreview').attr('src', data['path']);
               },
           error        :   function(data, status, e){
                alert(e);
               }                
           });

});

Ajax控制器:

public function uploadImage()
    {
        $status = "";
        $msg = "";
        $filename='';
        $file_element_name = 'txtURL';//Name of input field


        if (empty($_POST['title'])){
            $status = "error";
            $msg = "Please enter a title";
        }

        if ($status != "error"){

            $targetPath = ''.date('Y').'/'.date('m').'/';

            if(!file_exists(str_replace('//','/',$targetPath))){
                mkdir(str_replace('//','/',$targetPath), 0777, true);
            }

            $config['upload_path'] = $targetPath;
            $config['allowed_types'] = 'jpg|png|jpeg';
            $config['max_size'] = 150000;
            $config['file_name']=time(); //File name you want
            $config['encrypt_name'] = FALSE;

            $this->load->library('upload', $config);
            $this->upload->initialize($config);

            if(!$this->upload->do_upload($file_element_name)){
                $status = 'error';
                $msg = $this->upload->display_errors('', '');
            }
            else{
                $data = $this->upload->data();
                $filename = $targetPath.$data['file_name'];
            }
            //@unlink($_FILES[$file_element_name]);
        }

        echo json_encode(array('status' => $status, 'msg' => $msg,'path'=>$filename));
    }

添加Ajaxfileupload.js

答案 4 :(得分:0)

您无法使用AJAX直接上传图片

答案就是回应:

data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",