0
votes

I am using p-fileUpload primeng component. I have a requirement where in addition to the files selected another p-multiselect in the form has to be submitted along. Below is the working code for fileupload. When I choose and click upload it uploads the file. I want to change uploadFileCtr($event) to uploadFileCtr($event,faqForm.value ) and pass the commented code in uploadFileCtr() method in the ts file. i tried and added this line to the service.ts formdata:

formData.append("faqObj", faqObj);

However I couldnt get the object in my rest service. I tried to include another param in my POST method : @FormDataParam("faqObj") Faq . This gives me error.

My coponent.html look like this

<form [formGroup]="faqForm" >
    <div class="row">
                <div class="col-sm-4">
                    <p-fileUpload name="myfile[]" multiple="multiple" accept=".xlsx" customUpload="true"
                    (uploadHandler)="uploadFileCtr($event)">
                    </p-fileUpload>
                </div>
                <div class="col-sm-4">
                    <label >Board ID(s) *:</label>
                    <p-multiSelect [options]="boards" formControlName="board" [defaultLabel]="'All Active Boards'" (onChange)="displayBoard($event)"></p-multiSelect> 
                </div> 
                <div class="col-sm-4" *ngIf = "show">
                    <label >Board Title:</label>
                    <input class="pInputFilter pInputTxt" type="text" readonly id="boardname" value={{this.userSelectedBoard}}>  
                </div>
        
    </div>

</form>

component.cs for uploadFileCtr is as below

uploadFileCtr(event) { 
      // faqObj.faqBoards =  faqObj.board.map(boardId=>{
      //   let boardObj:Board = new Board();
      //   boardObj.id = boardId; 
      //   return boardObj;
      // });
        for(let file of event.files) {
          this.uploadedFiles.push(file);
        }
        this.faqService.uploadFile(this.uploadedFiles).subscribe( posts =>{
            this.data = posts;
        },
        error => console.log("Error: ", error),
        () => {
            this.errMsg = this.data.error; 
            // this.succMsg = this.data.success;  
            if (this.errMsg) {
                console.log("errMsg: ", this.errMsg);
                this.msgs = [];
                this.msgs.push({severity:'error', summary:'Error Message', detail:this.data.error});                
                this.status = "error";
            } else {
                // this.getCaseDocuments();
                this.msgs = [];
                this.msgs.push({severity:'success', summary:'Success Message', detail:this.data.success});                             
            }
        
        });
        this.faqForm.reset();
    }
    

Service.ts for the upload REST service is

uploadFile( uploadedFiles: any[]){
    let file: File = null;
    let formData:FormData = new FormData(); 
    if(uploadedFiles != null && uploadedFiles.length > 0){
        file = uploadedFiles[0];
    }      
    if(file != null){
        formData.append("file", file);
        formData.append("fileName", file.name);
    }else{
        formData.append("file", null);            
        formData.append("fileName", "");
    }
    return this.http.post(this.faqServiceURL +"/upload", formData, { 'headers': this.headers });
}

}

@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json")
public Response upload(@FormDataParam("file") InputStream is,
                           @FormDataParam("fileName") String fileName){
    logger.info("FaqService - upload");
    System.out.println("upload : "+fileName+"  faqObj : "); 
    ObjectMapper mapper = utilityObj.getMapperObj();
    String jsonInString = "";  ..//////
    
    }
  1. Can I add formobj along with the upload - if so, how?
  2. How can I send multiple files? formData.append("file", file); - this doesnt accept an array
1

1 Answers

2
votes

Question 1- Can I add formObj along with the upload - if so, how?

If you have to send the whole object in the formData there are 2 ways,

  1. Stringify the object like- formData.append("faqObj", JSON.stringify(faqObj)); In this case, the server will have to parse the stringified object.
  2. Another way to do it is to append the keys of the object looping through the object like Object.keys(faqObj).forEach(ele => formData.append(`faqObj[${ele}]`), faqObj[ele]) In this case, the server does not have to parse the object.

Question 2- How can I send multiple files? formData.append("file", file); - this doesnt accept an array

For this, you have to loop through the files array as follows

uploadedFiles.forEach(file => formData.append('file[]', file))