How can I submit a form right after a user chooses a picture?
I have a form and I'm trying to figure out how I can submit the form after the user uploads a picture and it is verified that it is a开发者_运维百科 picture. I am trying to use javascript to verify the image being uploaded.
Try this:
<script>
function submitFormAfterImageCheck()
{
if(/(\.jpeg|\.jpg|\.gif|\.png|\.tiff)$/.test(document.getElementById("myFile").value))
{
document.getElementById("myForm").submit();
}
else
{
alert("you can only upload an image");
}
}
</script>
And the HTML:
<input id="myFile" type="file" onchange="submitFormAfterImageCheck();" />
you can use an Iframe to handle the upload
<iframe src="upload.php" id="uploadHandler"></iframe>
and javascript to handle uploading/receiving status
var form = document.getElementById("avatar_form");
var inpUpload = document.getElementById("upload_button");
var fileSelector = document.getElementById("file_browser");
var uploadHandler = document.getElementById('uploadHandler');
inpUpload.onclick = function() {
form.target = uploadHandler;
uploadHandler.onload = function() {
alert(uploadHandler.document.body.innerHTML);
}
}
and in the php file upload.php
: check the $_FILES array if the uploaded file is ok and echo some response like:
$allowed_extensions = array("jpg", "png", "gif");
if (in_array(end(explode(".", $_FILES['file_browser']['filename'])), $allowed_extensions)) {
echo "upload OK";
}
else {
echo "invalid file";
}
not tested ... yet :)
You could check file extension on the client side and then decide whether to trigger submit for the form like so (jQuery style):
<script>
$(function(){
$('#fileDivId').change(function(){
$this = $(this);
if ($.inArray($this.val().split('.').pop().toLowerCase(), ['jpg', 'jpeg', 'png', 'gif']) != -1) {
$this.parent().trigger('submit');
}
});
});
</script>
<form action="post.php" method="POST">
<input type="file" id="fileDivId">
</form>
But there are some weak points here:
1) You still have to sanitize your images on server side
2) Not quite sure how $('inputId').val() works when input type is "file". For example firefox 4 returns file name, but if I remember correctly, IE will return full path of the file (C:\Docs\Img\etc), and furthermore it might be disabled in some browsers due to security reasons.
3) Getting extension part in my code is not perfect - concider situation: user selects file C:\Doc.img\file_no_ext, it returns "img\file_no_ext"
精彩评论