Home > other >  how to make the file upload selection block
how to make the file upload selection block

Time:02-01

I currently want the user to upload a file for some processing.

So, I have a form element as follows:

<form action="{{ url_for('test') }}" method="post" onSubmit="return submitDocument()">
    <button  id="upload-button" type="submit">Upload Document</button>
</form>

There is a corresponding file input object as:

<input type="file" (change)="fileEvent($event)"  id="embedfileinput" accept="image/*, application/pdf, application/msword" style="display:none"/>

and then I have the javascript as:

function showProcessing() {
     $('#processing').dimmer('show');
     return true;
}

function submitDocument() {
    document.getElementById('embedfileinput').click();
    showProcessing();
    return true;
}

The problem is that as soon as I click the upload button, the form gets submitted. What I would like to do is trigger the submission task after the file has been selected.

Is there a way to make this file selection blocking?

CodePudding user response:

A few things. As soon as you click the submit button and the button is inside the form tag, your form is gonna be submitted. That's default behavior. To prevent it, put a onclick="clickListener(event)" in your button and call event.preventDefault() to avoid this behaviour. Second, doing so will NOT trigger a onsubmit event in you form. So there's no sense having such attribute in the form. Try this:

<form action="{{ url_for('test') }}" method="post">
    <button  id="upload-button" type="submit" onclick="clickListener(event)">Upload Document</button>
</form>

in your javascript:

function clickListener(e) {
    // call your custom code here
    e.preventDefault();
}

Note that I removed onsubmit attibute from the form tag.

You can always call form.submit() to submit manually. More details https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

  • Related