Reputation: 1173
i have a page need to click a button to post a file, but the server get nothing??? can anyone help me?
<button class="btn btn-primary btn-sm" id="upload_item">上传</button>
$('#upload_item').click(function(event) {
event.preventDefault();
var form = $('<form action="." method="post" enctype="multipart/form-data" hidden> </form>').wrapInner(
$('<input type="file" value="" name="uploadfile">').click()).appendTo('body').submit().remove();
});
Upvotes: 0
Views: 96
Reputation: 125
As you are generating new DOM so instead of click event use $(document).on(); Thus you would able to handle the events for newly generated DOM. Hope following Scripts will work for you.
$(document).on('click', '#upload_item', function(event) {
event.preventDefault();
var form = $('<form action="#" method="post" enctype="multipart/form-data" > </form>').wrapInner(
$('<input type="file" value="" name="uploadfile" id="uploadfile">'
)).appendTo('body').hide();
var fileHandler = $('#uploadfile');
fileHandler.click();
fileHandler.change(function(event) {
$(this).val();
console.log($(this).val()); // Just Checking file is populated or not
form.submit();
});
});
And ++ if the problem is on server side to debug:
How do you check on server to get the value of this form ? Are you using $_POST or $_FILES ?
Try the following code on your server side code. (This is for php)
print_r($_FILES);
Analyse what you get on response. You will get a response like that
array (size=1)
'uploadfile' =>
array (size=5)
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
Check which error is creating this issue. File Upload error Messages
Hope this will be helpful.
Upvotes: 1
Reputation: 5191
Why don't you simply do this? if form is hidden how user will be able to click? Obviously no file will be uploaded.
<form action="." method="post" enctype="multipart/form-data">
<input type="file" value="" name="uploadfile">
</form>
Upvotes: 0