I had a form like this :
<form action="assets/php/test.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<div id="imgcont" hov="url('../data/img.svg')" >
<input type="file" name="clue" value=" " id="img" accept=".png,.jpg,.jpeg">
</div>
<input type="text" name="message" id="message">
<input type="submit" name="submit" value="" id="send">
</form>
And I don't know why but he always return an empty Array like this :
Array ( [clue] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) ) 0
-The name of the input file is good
-Here is no other iteartion of this name in my code
I rewrite the code to delete all unusefull things
<form action="assets/php/Send_Message.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="clue" id="fileToUpload" value=" " id="img" accept=".png,.jpg,.jpeg" >
<input type="text" name="message" id="message">
<input type="submit" value="" name="submit">
</form>
<?php
print_r($_POST);
echo '</br>';
print_r($_FILES);
?>
-The file is here because I use JS to show a preview of this image
function updateImageDisplay() {
var curFiles = input.files;
if(curFiles.length === 0) {
preview.style.backgroundColor = "#ff4c42";
} else {
for(var i = 0; i < curFiles.length; i++) {
if(validFileType(curFiles[i])) {
var image = document.createElement('img');
image.src = window.URL.createObjectURL(curFiles[i]);
} else {
console.log("File Type Not Valid");
}
preview.style.backgroundImage = "url("+image.src+")"
preview.innerHTML += '<span onclick="Reinit()" class="delete" id="cl" >X</span>' ;
}
}
}
var fileTypes = [
'image/jpeg',
'image/pjpeg',
'image/png'
]
function validFileType(file) {
for(var i = 0; i < fileTypes.length; i++) {
if(file.type === fileTypes[i]) {
return true;
}
}
return false;
}
the problem comes from this two lines in my js
var image = document.createElement('img');
image.src = window.URL.createObjectURL(curFiles[i]);
It's like my js just take the imlage and not copying it.
Make sure the php.ini directives upload_max_filesize, post_max_size are larger than the file you are trying to upload. Also make sure that file_uploads isset to 1 and max_file_uploads to something larger than 0.
This error may also occur if you have nested multiple forms inside each other.
Related
Learning Javascript and trying to work out the best way to validate a text and number fields on a form.
I have the following html form:
> <form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br>
<input class="input input1" type="text" id="setName" name="setName" value=" ">*<br>
<label for="setTheme">Set Theme</label><br>
<input class="input input1" type="text" id="setTheme" name="setTheme" value=" "><br>
<label for="setReferenceNumber">Reference Number</label><br>
<input class="input input1" type="number" id="setReferenceNumber" name="setReferenceNumber" value="0">*<br>
<label for="setPieceCount">Piece Count</label><br>
<input class="input input1" type="number" id="setPieceCount" name="setPieceCount" value="0">*<br>
<br>
<input class="input input2" type="button" value="Save Set" onclick="captureLegoSets.captureSets()">
<input class="input input2" type="reset" value="Reset Values">
</form>
And attached Javascript (forgive the numerous console.log statements):
this.captureSets = function(){
let setName = " ";
let setTheme = " ";
let setReferenceNumber = 0;
let setPieceCount = 0;
let formFields = document.querySelectorAll(".input1");
console.log(formFields);
for (let i=0; i < formFields.length; i++) {
console.log(formFields[i]);
console.log(formFields[i].id);
console.log(formFields[i].value);
if ((+document.getElementById(formFields[i].id).value) > 0 | (+document.getElementById(formFields[i].id).length) !== null) {
console.log(formFields[i].id + " = " + formFields[i].value);
if(formFields[i].id === "setName"){
setName = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = +document.getElementById(formFields[i].id).value;
}
console.log(formFields);
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
}
The problem I'm experiencing if that the else statement keeps triggering for the text fields if I only check the .value, but if I check the .length, it doesn't trigger at all.
I know I could probably put together a bunch of if statements to check for null, empty and so on, but I'm assuming this would just be poor coding on my part. Is there a better/more concise way of checking for valid inputs?
First you have provided default values to all your text fields, which let the following if check resulting in true, since you have provided default values as " " ( " " is not a null )
if ((document.getElementById(formFields[i].id).value > 0) || (document.getElementById(formFields[i].id).length !== null))
In the above expression you have used !== instead of !=
You used | not || for or operation
Remove + before document ( I don't understand why you have added those. Please explain
Hence,
remove default values / check for right conditions in the conditional statements,
use a p tag to display all the errors in the bottom. I have provided a simple example of concatenating the errors, you can also use an array to collect the errors. In the best case a separate error text right below each text field is awesome.
HTML
<form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br />
<input
class="input input1"
type="text"
id="setName"
name="setName"
/>*<br />
<label for="setTheme">Set Theme</label><br />
<input
class="input input1"
type="text"
id="setTheme"
name="setTheme"
/><br />
<label for="setReferenceNumber">Reference Number</label><br />
<input
class="input input1"
type="number"
id="setReferenceNumber"
name="setReferenceNumber"
/>*<br />
<label for="setPieceCount">Piece Count</label><br />
<input
class="input input1"
type="number"
id="setPieceCount"
name="setPieceCount"
/>*<br />
<br />
<input
class="input input2"
type="button"
value="Save Set"
onclick="captureSets()"
/>
<input class="input input2" type="reset" value="Reset Values" />
</form>
<p id="error-text"></p>
JS
captureSets = function () {
let setName = "";
let setTheme = "";
let setReferenceNumber = 0;
let setPieceCount = 0;
let errorText = "";
let formFields = document.querySelectorAll(".input1");
for (let i = 0; i < formFields.length; i++) {
if (
(document.getElementById(formFields[i].id).value > 0) ||
(document.getElementById(formFields[i].id).length != null)
) {
if (formFields[i].id === "setName") {
setName = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = document.getElementById(
formFields[i].id
).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = document.getElementById(formFields[i].id).value;
}
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
if (!setName || setName == "") {
errorText += " Fill the name text field <br>";
}
if (!setPieceCount) {
errorText += " Fill the piece count text field <br>";
}
if (!setTheme || setTheme == "") {
errorText += " Fill the theme text field <br>";
}
if (!setReferenceNumber) {
errorText += " Fill the reference number text field <br>";
}
document.getElementById("error-text").innerHTML = errorText;
};
This may or may not help you, but I think, this is easier for you to check this directly by pattern attribute. You just need to put some regex.
An HTML form with an input field that can contain only three letters (no numbers or special characters):
<form>
<label for="country_code">Country code:</label>
<input
type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}"
title="Three letter country code">
</form>
https://www.w3schools.com/tags/att_input_pattern.asp
I have multiple browse button. I want to show Apply button when I upload file from at least 4 browse button. I can check length of file when I upload file from single browse button. But how can I check files length when I upload files from multiple uploads.
Here is my HTML code:
<input type="file" class="files" name="file" /> Read bytes:
<input type="file" class="files" name="file" /> Read bytes:
<input type="file" class="files" name="file" /> Read bytes:
<input type="file" class="files" name="file" /> Read bytes:
<span class="readBytesButtons">
<button>Apply</button>
</span>
Here is my JavaScript code:
var allFiles = document.getElementsByClassName('files');
if (allFiles.length > 4) {
alert('Please select a file!');
} else {
// code to show apply button
}
It's not working well. How can I found the length of total uploaded file?
You can add an event listener to the "change" event of the input elements.
When this event is triggered, you can loop the fileElements and check the number of files using files.length.
You can then keep track of the number of elements that have more than 0 files.
If all elements have an uploaded file, you can enable the button.
For example:
var fileElements = document.getElementsByClassName('files');
for (var i = 0; i < fileElements.length; i++) {
fileElements[i].addEventListener("change", countFiles);
}
function countFiles() {
var elementsWithFiles = 0;
for (var j = 0; j < fileElements.length; j++) {
if (fileElements[j].files.length > 0) {
elementsWithFiles++;
}
}
if (elementsWithFiles > fileElements.length -1) {
document.getElementById("readBytesButtons").style.display = "block";
}
}
.readBytesButtons {
display: none;
}
<form id="" name="">
<input type="file" class="files" name="file"/> Read bytes:
<input type="file" class="files" name="file"/> Read bytes:
<input type="file" class="files" name="file"/> Read bytes:
<input type="file" class="files" name="file"/> Read bytes:
<span class="readBytesButtons" id="readBytesButtons">
<button>Apply</button>
</span>
</form>
If you want to check the amount of files inserted you most likely would need to add an event listener to each of the file inputs. Then increasing when an file gets inserted and then check if the required amound is added you would probably end up with something like this:
var insertedFiles = 0;
var allFileElements = document.getElementsByClassName('files');
for (var i = allFileElements.length - 1; i >= 0; i--) {
allFileElements[i].addEventListener("change",check);
};
function update(){
if(this.value == "") {
insertedFiles--;
} else {
insertedFiles++;
}
check();
}
function check(){
if(insertedFiles > 4){
alert("Show button.");
} else {
alert("You need to add more files.");
}
}
fiddle: https://jsfiddle.net/aL0qhoe0/2/
I'm trying to check whether the user has actually chosen a file before pressing on upload or not, if so then check if the file is bigger than 4 MB. If the user has pressed on upload without choosing a file then a message should be sent telling them to go back and choose a file. But this code doesn't seem to work.
<div id="postUpload-wrapper">
<form id="uploadpost-form" action="/uploadpost" enctype="multipart/form-data" method="POST">
<input type="text" id="postname" placeholder="Title" name="postname">
<br>
<input id="fileupload" type="file" name="image">
<br>
<input type="submit" id "uploadpost-btn" value="Upload" name="uploadpost">
</form>
</div>
//UPLOAD A POST
router.post('/uploadpost', upload.single('image'), function(req, res){
var errors = "";
if(req.body.postname === ""){
errors += "Write a title";
res.send(errors);
return false;
}
//problem here
if(req.file.size === 0){
errors += "You need to choose a file";
res.send(errors);
return false;
}else{
if(req.file.size > 4000000){
errors += "Files can only be up to 4 MB in size";
res.send(errors);
return false;
}
}
Try setting input type="submit" element property disabled to "true" , use onchange event of input type="file" element to check if user selected file at FileList object , set type="submit" element to disabled="true" , disabled="false" if file.size greater than 4000000 bytes . If file not selected , file size over 4000000 bytes submit button set to disabled
var input = document.getElementById("fileupload");
input.onchange = function() {
var file = this.files, submit = this.nextElementSibling.nextElementSibling;
if (file.length > 0) {
if (file[0].size >= 4000000) {
submit.disabled = true;
alert("file size limit")
} else {
submit.disabled = false;
console.log(this.files)
}
}
}
<div id="postUpload-wrapper">
<form id="uploadpost-form" action="/uploadpost" enctype="multipart/form-data" method="POST">
<input type="text" id="postname" placeholder="Title" name="postname">
<br>
<input id="fileupload" type="file" name="image">
<br>
<input type="submit" id="uploadpost-btn" value="Upload" name="uploadpost" disabled="true">
</form>
</div>
I believe you should check this on the client side before allowing the file to be uploaded.
if(document.getElementById("uploadpost-btn").value != "") {
// you have a file
}
You can later check on the server-side. If req.body has any data then there was a file uploaded.
I have this form in html for multiple file uploading .
<form class="userform" method="post" action="upload.php" role="form" enctype="multipart/form-data" >
<input name="title" type="text" ><br/>
<input type="file" name="media[]" >
<div class="filesupload">
<input type="file" name="media[]" >
</div>
<script>
$(document).on("click",".add-new-file",function()
{
$('.filesupload').append('<input name="media[]" type="file" >');
});
</script>
</form>
I will get input files by javascript and send to upload.php for uploading. but I don't know how to get files values in javascript.
If you using HTML5
var fileList = document.getElementById("yourInput").files;
for(var i = 0; i < fileList.length; i++) {
//Do something with individual files
}
Using jquery
$("input[name=file1]").change(function() {
var names = [];
for (var i = 0; i < $(this).get(0).files.length; ++i) {
names.push($(this).get(0).files[i].name);
}
$("input[name=file]").val(names);
});
I currently have a file element, and a button that allows a user to add more file elements so that if they wanted to, they could select multiple at once. I want to be able to loop through them and need some assistance as to what direction I should take or if there is a correct syntax to do this. Form, php, and JS code below.
Form:
<form action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" method="post" enctype="multipart/form-data" name="upload_form" id="upload_form">
<br />
<input type="file" name="file[]" id="file"/>
<input id="addbutton" type="button" onclick = 'javascript: add()' value="ADD ANOTHER FILE" />
<br />
<input type="submit" id="submit" name="submit" value="SUBMIT" />
</form>
PHP:
if($_POST['submit'] == "SUBMIT")
{
$count = count($_FILES[ "file" ][ "tmp_name" ]);
echo $count;
for($i = 0; $i < $count; ++$i)
{
if($_FILES && $_FILES['file']['name'])
{
//code that does some stuff here
}
}
}
JS:
<script>
function add()
{
var form = document.getElementById("upload_form");
var addButton = document.getElementById('addbutton');
var br = document.createElement("br");
form.insertBefore(br, addButton);
form = document.getElementById("upload_form");
input = document.createElement("input");
input.type="file";
input.name="file[]";
form.insertBefore(input, addButton);
}
every thing is looks ok, u just need to add index to access particully uploaded file like
<?php
// ...
for($i = 0; $i < $count; ++$i)
{
echo $_FILES['file']['tmp_name'][$i];
// ...
Looks perfect, but you can just use this for multiple selection:
<input type="file" name="file[]" id="file" multiple="multiple" />
You won't need that javascript...