0

I have a upload attachment in react spfx , need to validate file based on the type, it should only allow pdf files other extensions should trigger an alert. I have added accept =".pdf" in input of the file, it does filter the extension to pdf but if the user changes it, it still accepts other file type, how to add validation to check the extension type before form submit? below is the attachment file code.

              <Label ><h3><b>Please upload PDF files only</b></h3></Label>
                <input type="file" accept=".pdf" name="file-1[]" id="file-1" hidden
                  multiple
                  onChange={(e) => this.OnfileChange(e)}
                />
                <Label required htmlFor="file-1" className={styles.fileBrowse}><FaUpload />
                  <span>&nbsp;Upload Attachment</span></Label>
              </div>
            </div>}
            <div className={styles.row}>
              <ul className="DocsData">
                {this.state.uploadedDocsList.map(colorItem => {
                  return (<li className="listStyle">
                    <a href={colorItem.ServerRelativeUrl} target="_blank" data-interception="off" className={styles.docslinK}>
                      <FileTypeIcon type={IconType.image} path={colorItem.ServerRelativeUrl} />
                      {colorItem.FileName}</a>
                    <button hidden={this.state.FormType == "DISP"} className="deleteButton btn-danger"
                      onClick={() => this.OnDocsDelete(colorItem.FileName)}
                      style={{ margin: "2px 6px", "border": 0 }} >X</button></li>);
                })}
              </ul>

            </div>
          </div> ```

``` /* this method to for uploading select files to collection object */
  private UploadFiles() {
    // totDocsFiles = [];
    uploadedDocsList = this.state.uploadedDocsList;
    for (var Count = 0; Count < files.length; Count++) {
      var file = files[Count];
      var FileName = files[Count].name;
      let filterCheck = this.state.uploadedDocsList.filter((element) => {
        if (FileName == element.FileName) {
          return element;
        }
      });
      if (filterCheck.length == 0) {
        uploadedDocsList.push({
          'FileName': FileName,
          'ServerRelativeUrl': '#'
        });
        totDocsFiles.push({
          name: FileName,
          content: file
        });
      }
    }

    this.setState({ uploadedDocsList: uploadedDocsList });
  }

  /* this method to handle document delete on file upload controle */
  private OnDocsDelete(docName) {
    let totDocsFilesTemp: string[] = [];
    uploadedDocsList = this.state.uploadedDocsList.filter((enteringItem) => {
      if (enteringItem.FileName != docName) {
        return enteringItem;
      }
      else {
        if (enteringItem.ServerRelativeUrl != "#") {
          docstoDelete.push(enteringItem.FileName);
        }
        else {
          totDocsFilesTemp = totDocsFiles.filter((totDocsFile) => {
            if (totDocsFile.name != docName) {
              return totDocsFile;
            }
          });
          totDocsFiles = totDocsFilesTemp;
        }
      }
    });
    this.setState({ uploadedDocsList: uploadedDocsList });
  }

  private onFormatDate(date?: Date): string {
    return !date ? '' : moment(date.toISOString()).format('MM/DD/YYYY');
  } ```
1

I have tried this code

 <div class="${ styles.row }">
            <div class="${ styles.column }">
            <Label ><h3><b>Please upload PDF files only</b></h3></Label>
                 <br/>
                <input type="file" accept=".pdf" name="file-1[]" id="file-1" 
                multiple  >
            </div>
          </div>

and it is working , It accepts the pdf files only , validation code is also applied

UI to select files

File selection

Use the following code to validate the files

 private OnfileChange(event: Event): boolean {
    var files = (<HTMLInputElement>event.target).files;
    var allowedExtensions = /(\.pdf)$/i;
    for (var f = 0; f < files.length; f++) {
      if (!allowedExtensions.exec(files[f].name)) {
        alert('Invalid file type');
        // clear the file upload here
        return false;
      }
    }
    return true;
  }
3
  • ya but if u select , all files and select other document file type it will allow that file to be uploaded , need validation when they select other file types..
    – biggie
    Sep 24 '21 at 2:25
  • 1
    This worked for me in onfileonchage method ` for (let i = 0; i < netFiles.length; i++) { if (netFiles[i].name.split('.').pop().toLowerCase() != 'pdf') { isOtherFile=true; } } if(isOtherFile){ alert("Please select only pdf files.") return; }`
    – biggie
    Sep 24 '21 at 4:19
  • great it worked for you. I was about to post the solution ( same as yours ) that I just did. I am updating the answer in case someone wants to know the solution
    – Saira
    Sep 24 '21 at 4:36
0

In OnfileChange method , this validation works

      if (netFiles[i].name.split('.').pop().toLowerCase() != 'pdf') {
        isOtherFile=true;
      }
    }
    if(isOtherFile){
      alert("Please select only pdf files.")
      return;
    } ``` 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.