使用ajax上传图像,无需使用表单

Upload an image with ajax without using a form

本文关键字:表单 ajax 图像 使用      更新时间:2023-12-21

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

我有一个表单,用户可以从下拉列表中选择一个图像。我想让用户在填写表格时可以动态添加另一个图像。然后,新图像将作为选项添加到下拉列表中,用户可以选择它。

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

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

数据库中的表将具有:id-name-path_to_file

通常我使用jqueryForm插件来上传新的图像,这个插件会寻找一个带有<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,也不会起作用。

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

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

如果你绝对想先上传图片,请使用AJAX。jQuery可以从输入中获得值,而无需考虑表单的其余部分:

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

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

请注意,这只适用于HTML5兼容的浏览器。旧的浏览器不能用这种方式通过AJAX发送文件。

在此过程中指出以下步骤:

  1. 包括jQuery库。

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

  3. jQuery Ajax代码。

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

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>";
}
}
?>