Home > OS >  I need to pass an empty string, and not Null in my FormData.append()
I need to pass an empty string, and not Null in my FormData.append()

Time:08-13

I am working on the frontend for this project with limited access to the backend code and debugging in Java so I may be confused on what is going on. Also, I'm not a Java expert yet, but here's the situation as I've been told by my Java counterpart.

When I'm submitting a form from Angular to the Java api, I have 2 files that are uploaded. One is required, the other is optional. If the param in the form comes in as Null for the optional param in Java, it throws a Null Pointer Exception. The Java has a check for if the object is empty I believe. I only got a brief look at the debugger today so can't tell you for sure.

I have an if condition checks all of the values of the form and appends them to the FormData object before submitting the form. Because formData.append(value, '') converts all empty strings to Null, when my optional document is empty, it appends null to the value, causing the error. If the optional document is selected, the error does not happen.

This is my condition:

for(let value in form) {
if(form[value] instanceof Object){
    let blob = new Blob([form[value][0].raw], {type:form[value][0].extension})
    formData.append(value, blob, form[value][0].name)
}else{
    formData.append(value, form[value])
}

Is there a way to set this so it hits Java as an empty string and not null? Or maybe I misunderstand what is happening on the Java side? Should it be an empty object, and not a string? If so, how do I set the value as an empty object?

CodePudding user response:

One of the alternatives is to do an if to check if form[value][0].extension alone. Change your conditional for:

if (!form[value][0].extension.isEmpty()){
    //your code
}

CodePudding user response:

Creating a new empty Blob and appending it to the form worked.

    for(let value in form) {
      if(form[value] instanceof Object){
        let blob = new Blob([form[value][0].raw], {type:form[value] [0].extension})
        formData.append(value, blob, form[value][0].name)
      }else if (value === "supportingDocument"){
         let blob = new Blob()
         formData.append(value, blob)
    
      } else {
          formData.append(value, form[value])
      }
  • Related