I know that form nesting is not a valid option for html5 (and generally for html) so I'd like to understand how can I do a file upload inside a form without using another form.
我知道表单嵌套不是html5(通常是html)的有效选项,所以我想了解如何在不使用其他表单的情况下在表单中进行文件上传。
I have a form where the user can choose one image from a dropdown. I'd like to give the user the ability to add another image on the fly while filling the form. The new image will be then added as an option to the dropdown and the user can choose it.
我有一个表单,用户可以从下拉列表中选择一个图像。我想让用户在填写表单时动态添加另一个图像。然后,新图像将作为选项添加到下拉列表中,用户可以选择它。
EDIT: when I say "choose an image from a dropdown" I mean that the images are stored on the server on a specific folder. In the dropdown I show the files name (stored in a db). Adding a new image to the folder will add it to the db to and will add the new image name to the select. But each select option will just be:
编辑:当我说“从下拉列表中选择图像”时,我的意思是图像存储在特定文件夹上的服务器上。在下拉列表中,我显示了文件名(存储在数据库中)。将新图像添加到文件夹会将其添加到数据库中,并将新图像名称添加到选择中。但每个选择选项将只是:
<option value="id_from_db">Image_name_from_db</option>
and the table in the db will have: id - name - path_to_file
并且db中的表将具有:id - name - path_to_file
Usually I use the jquery Form plugin to upload the new image and this plugin looks for a form with the <input type="file">
tag to do the upload. Is there any chance to upload the image without the nested form? I was thinking about using an iframe but this looks like a crazy idea. The actual html structure looks like:
通常我使用jquery Form插件上传新图像,这个插件会查找带有标签的表单来进行上传。有没有机会上传没有嵌套表格的图像?我在考虑使用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>
I have no issue posting the main form, I have no issue adding the new file as an option to the select. But this structure is not a valid html and will not work.
我没有发布主表单的问题,我没有问题添加新文件作为选项的选项。但是这个结构不是有效的html,也不行。
2 个解决方案
#1
2
Following steps are pointed under this process :
以下步骤指向此过程:
-
Include jQuery library.
包括jQuery库。
-
HTML page with upload field.
带上传字段的HTML页面。
-
jQuery Ajax code.
jQuery Ajax代码。
-
PHP script to store image.
用于存储图像的PHP脚本。
Ajax Code:
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 code used to store the image:
用于存储图像的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 file : ajax_upload_image_main.php
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>
Complete jQuery Code : script.js
完整的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 Script : ajax_php_file.php
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>";
}
}
?>
#2
2
You can use the readAsDataURL
method to display the image in the dropdown. Or just add an option that reads something like "use own image" after the user used the file input to upload an image.
您可以使用readAsDataURL方法在下拉列表中显示图像。或者只是在用户使用文件输入上传图像后添加一个类似“使用自己的图像”的选项。
Then you can just post the form as normal, containing both the user's image and the information that he wants to use it. Connecting the two bits of information will happen on the server side.
然后您可以正常发布表单,包含用户的图像和他想要使用它的信息。连接两位信息将在服务器端进行。
If you absolutely want to upload the image first, use AJAX. jQuery can get the value from the input without considering the rest of the form:
如果您绝对想首先上传图像,请使用AJAX。 jQuery可以从输入中获取值而不考虑表单的其余部分:
$(imageInput).on('change', function(){
var data = this.files[0];
$.post(imagePostUrl, data);
});
In the html, either put the imageInput outside your form, or remove the image input from your form data with Javascript when the form is submitted, if you don't want your image to be uploaded again.
在html中,要么将imageInput放在表单之外,要么在提交表单时使用Javascript从表单数据中删除图像输入,如果您不希望再次上载图像。
Please note that this will only work in HTML5 compliant browsers. Older browsers can't send files via AJAX this way.
请注意,这仅适用于HTML5兼容的浏览器。较旧的浏览器无法通过这种方式通过AJAX发送文件。
#1
2
Following steps are pointed under this process :
以下步骤指向此过程:
-
Include jQuery library.
包括jQuery库。
-
HTML page with upload field.
带上传字段的HTML页面。
-
jQuery Ajax code.
jQuery Ajax代码。
-
PHP script to store image.
用于存储图像的PHP脚本。
Ajax Code:
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 code used to store the image:
用于存储图像的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 file : ajax_upload_image_main.php
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>
Complete jQuery Code : script.js
完整的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 Script : ajax_php_file.php
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>";
}
}
?>
#2
2
You can use the readAsDataURL
method to display the image in the dropdown. Or just add an option that reads something like "use own image" after the user used the file input to upload an image.
您可以使用readAsDataURL方法在下拉列表中显示图像。或者只是在用户使用文件输入上传图像后添加一个类似“使用自己的图像”的选项。
Then you can just post the form as normal, containing both the user's image and the information that he wants to use it. Connecting the two bits of information will happen on the server side.
然后您可以正常发布表单,包含用户的图像和他想要使用它的信息。连接两位信息将在服务器端进行。
If you absolutely want to upload the image first, use AJAX. jQuery can get the value from the input without considering the rest of the form:
如果您绝对想首先上传图像,请使用AJAX。 jQuery可以从输入中获取值而不考虑表单的其余部分:
$(imageInput).on('change', function(){
var data = this.files[0];
$.post(imagePostUrl, data);
});
In the html, either put the imageInput outside your form, or remove the image input from your form data with Javascript when the form is submitted, if you don't want your image to be uploaded again.
在html中,要么将imageInput放在表单之外,要么在提交表单时使用Javascript从表单数据中删除图像输入,如果您不希望再次上载图像。
Please note that this will only work in HTML5 compliant browsers. Older browsers can't send files via AJAX this way.
请注意,这仅适用于HTML5兼容的浏览器。较旧的浏览器无法通过这种方式通过AJAX发送文件。