inputfile-uploadlabelpug

pug template how to use a label of a hidden file input to upload file?


I use pug template with Node.JS. How can I use a label to hide file input control and use the label click to upload file? I have done the same thing using bootstrap but not sure about about to accomplish this on pug template. Bootstrap 5.3.5 Hide input[type='file'] with a button

My current file input:

p.control
    input(class='input', id='image', name="image", type='file', accept="image/*")

and I want it to be something like the following using Bootstrap:

<div class="col-md-1 d-flex justify-content-center">
  <label id="lbl-upload" class="btn btn-outline-secondary" for="image" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Upload an image for your question">Upload</label>
  <input id='image' name="image" type='file' class="form-control" accept="image/*" style='width:0;' placeholder="Upload an image for your question" aria-describedby="btn-upload" aria-label="Upload" hidden/>
</div>

I tried David's suggestion but the input is not really hidden as shown in the picture: file input is not hidden

code:

              form#chatForm(action='/api/gemini', method='post', enctype="multipart/form-data")
                .field.has-addons
                  p.control.is-expanded
                    input(class='input', id='prompt', type='text', placeholder='How can I help?', onkeyup="stoppedTyping()")
                  p.control
                    label.file-label(class='input', for="file-upload") Choose File
                    input.file-input(class='input', id="file-upload", name="file-upload", type="file", accept="image/*", hidden="hidden")
                  p.control
                    input.receipt-input(class='input', id="receipt", name="receipt", type="checkbox", value="")
                    label.receipt-label(class='input', for="receipt") Receipt
                  p.control
                    input(class='button is-success', id="submit", type='submit', value='Submit')

Solution

  • The HTML structure you're looking to create is simply an <input type="file"> and a <label> associated with that input. In Put that can be as simple as:

    label.file-label(for="file-upload") Choose File
    input.file-input(type="file" id="file-upload")
    

    And if you want to hide an element, style it to be hidden with CSS:

    #file-upload {
     display: none;
    }
    

    You can further apply any styling you want on the label, of course. If you want it to look like a button or have specific style needs to apply for consistency, it can be styled like any other element(s) in your application.


    Or, if not with CSS, you can even just use the hidden attribute on the <input> element:

    label.file-label(for="file-upload") Choose File
    input.file-input(type="file" id="file-upload", hidden="hidden")