admin管理员组

文章数量:1290132

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.

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

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:

<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.

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.

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

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:

<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.

Share Improve this question edited Apr 5, 2016 at 7:51 Lelio Faieta asked Apr 5, 2016 at 7:41 Lelio FaietaLelio Faieta 6,6849 gold badges47 silver badges84 bronze badges 4
  • What you describe all sounds possible, however this: The new image will be then added as an option to the dropdown and the user can choose it. is a problem. To upload a file you need to be able to get its binary data from a file input. All a select will give you is a string value, therefore you would need some method of keeping a hidden file input to match any chosen option from the select. – Rory McCrossan Commented Apr 5, 2016 at 7:44
  • @RoryMcCrossan I will save the image as a file in a folder. In the db i'll save the image name and the folder path. In the select user will see the image name from the db as an option and the id of the record as a value. The file itself will lay only in the folder and will later be used (the main form is to define the contents of an html page). Hope this will make more sense. :) – Lelio Faieta Commented Apr 5, 2016 at 7:46
  • 1 I don't know jQuery Form, but WebAPI has a FormData object that may help you. On submit of the main form, block the event, send the image as a blob, wait for server response and construct a new FormData with the remaining information, or add the new <option> with the in response new id. – Kaiido Commented Apr 5, 2016 at 7:51
  • @LelioFaieta have you tried this stackoverflow./questions/19447435/ajax-upload-image – Heemanshu Bhalla Commented Apr 5, 2016 at 7:55
Add a ment  | 

2 Answers 2

Reset to default 3

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.

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:

$(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.

Please note that this will only work in HTML5 pliant browsers. Older browsers can't send files via AJAX this way.

Following steps are pointed under this process :

  1. Include jQuery library.

  2. HTML page with upload field.

  3. jQuery Ajax code.

  4. PHP script to store image.

Ajax Code:

$.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:

$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>
<head>
<title>Ajax Image Upload Using PHP and jQuery</title>
<link rel="stylesheet" href="style.css" />
<link href='http://fonts.googleapis./css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis./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

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

本文标签: javascriptUpload an image with ajax without using a formStack Overflow