使用ajax上传图像而不使用表单

时间:2016-04-05 07:41:18

标签: javascript jquery html ajax

我知道表单嵌套不是html5的有效选项(通常用于html),所以我想了解如何在不使用其他表单的情况下在表单中上传文件。

我有一个表单,用户可以从下拉列表中选择一个图像。我希望用户能够在填写表单时动态添加其他图像。然后,新图像将作为选项添加到下拉列表中,用户可以选择它。

编辑:当我说"从下拉菜单中选择一张图片"我的意思是图像存储在特定文件夹上的服务器上。在下拉列表中,我显示了文件名(存储在数据库中)。将新图像添加到文件夹会将其添加到数据库中,并将新图像名称添加到选择中。但每个选择选项都只是:

<option value="id_from_db">Image_name_from_db</option>

并且db中的表将具有:id - name - path_to_file

通常我使用jquery Form plugin上传新图片,此插件会查找带有<input type="file">标记的表单进行上传。有没有机会上传没有嵌套表格的图像?我在考虑使用iframe,但这看起来像个疯狂的想法。实际的html结构如下:

<form>
    //some more stuffs for the main form
    <select name="image">
        <option>existing options</option>
    </select>
    <form>
        <input type="file">
        <button>Upload file</button>
    </form>
    //some more stuffs for the main form
    <button>Submit form</button>
</form>

我没有发布主表单的问题,我没有问题添加新文件作为选项的选项。但是这个结构不是一个有效的HTML,也不会起作用。

2 个答案:

答案 0 :(得分:2)

您可以使用readAsDataURL方法在下拉列表中显示图片。或者只是添加一个类似&#34的选项;使用自己的图像&#34;用户使用文件输入上传图像后。

然后您可以正常发布表单,包含用户的图像和他想要使用它的信息。连接两位信息将在服务器端进行。

如果您想首先上传图片,请使用AJAX。 jQuery可以从输入中获取值而不考虑表单的其余部分:

$(imageInput).on('change', function(){
    var data = this.files[0];
    $.post(imagePostUrl, data);
});

在html中,要么将imageInput放在表单之外,要么在提交表单时使用Javascript从表单数据中删除图像输入,如果您不希望再次上传图像。

请注意,这仅适用于符合HTML5标准的浏览器。较旧的浏览器无法通过这种方式通过AJAX发送文件。

答案 1 :(得分:2)

此流程指出了以下步骤:

  1. 包含jQuery库。

  2. 带有上传字段的HTML页面。

  3. jQuery Ajax代码。

  4. 用于存储图像的PHP脚本。

  5. Ajax代码:

    $.ajax({
        url: "ajax_php_file.php", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {
            $('#loading').hide();
            $("#message").html(data);
        }
    });
    

    用于存储图像的PHP代码:

    $sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable
    $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
    move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file
    

    HTML文件:ajax_upload_image_main.php

    <html>
    <head>
    <title>Ajax Image Upload Using PHP and jQuery</title>
    <link rel="stylesheet" href="style.css" />
    <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="script.js"></script>
    </head>
    <body>
    <div class="main">
    <h1>Ajax Image Upload</h1><br/>
    <hr>
    <form id="uploadimage" action="" method="post" enctype="multipart/form-data">
    <div id="image_preview"><img id="previewing" src="noimage.png" /></div>
    <hr id="line">
    <div id="selectImage">
    <label>Select Your Image</label><br/>
    <input type="file" name="file" id="file" required />
    <input type="submit" value="Upload" class="submit" />
    </div>
    </form>
    </div>
    <h4 id='loading' >loading..</h4>
    <div id="message"></div>
    </body>
    </html>
    

    完整的jQuery代码:script.js

    $(document).ready(function (e) {
    $("#uploadimage").on('submit',(function(e) {
    e.preventDefault();
    $("#message").empty();
    $('#loading').show();
    $.ajax({
    url: "ajax_php_file.php", // Url to which the request is send
    type: "POST",             // Type of request to be send, called as method
    data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
    contentType: false,       // The content type used when sending data to the server.
    cache: false,             // To unable request pages to be cached
    processData:false,        // To send DOMDocument or non processed data file it is set to false
    success: function(data)   // A function to be called if request succeeds
    {
    $('#loading').hide();
    $("#message").html(data);
    }
    });
    }));
    
    // Function to preview image after validation
    $(function() {
    $("#file").change(function() {
    $("#message").empty(); // To remove the previous error message
    var file = this.files[0];
    var imagefile = file.type;
    var match= ["image/jpeg","image/png","image/jpg"];
    if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
    {
    $('#previewing').attr('src','noimage.png');
    $("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
    return false;
    }
    else
    {
    var reader = new FileReader();
    reader.onload = imageIsLoaded;
    reader.readAsDataURL(this.files[0]);
    }
    });
    });
    function imageIsLoaded(e) {
    $("#file").css("color","green");
    $('#image_preview').css("display", "block");
    $('#previewing').attr('src', e.target.result);
    $('#previewing').attr('width', '250px');
    $('#previewing').attr('height', '230px');
    };
    });
    

    PHP脚本:ajax_php_file.php

    <?php
    if(isset($_FILES["file"]["type"]))
    {
    $validextensions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
    ) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
    && in_array($file_extension, $validextensions)) {
    if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
    }
    else
    {
    if (file_exists("upload/" . $_FILES["file"]["name"])) {
    echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
    }
    else
    {
    $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
    $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
    move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
    echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
    echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
    echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
    echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
    }
    }
    }
    else
    {
    echo "<span id='invalid'>***Invalid file Size or Type***<span>";
    }
    }
    ?>