简体   繁体   English

primeng fileUpload 发送表单数据并将文件数组传递给服务层

[英]primeng fileUpload to send form data and passing file array to the service layer

I am using p-fileUpload primeng component.我正在使用 p-fileUpload primeng 组件。 I have a requirement where in addition to the files selected another p-multiselect in the form has to be submitted along.我有一个要求,除了选择的文件之外,还必须提交表单中的另一个 p-multiselect。 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.我想将 uploadFileCtr($event) 更改为 uploadFileCtr($event,faqForm.value ) 并在 ts 文件的 uploadFileCtr() 方法中传递注释代码。 i tried and added this line to the service.ts formdata:我尝试将此行添加到 service.ts formdata:

formData.append("faqObj", faqObj);

However I couldnt get the object in my rest service.但是我无法在我的 rest 服务中获得 object。 I tried to include another param in my POST method: @FormDataParam("faqObj") Faq .我试图在我的 POST 方法中包含另一个参数: @FormDataParam("faqObj") Faq This gives me error.这给了我错误。

My coponent.html look like this我的 coponent.html 看起来像这样

<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 的 component.cs 如下

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用于上传 REST 服务的 Service.ts 是

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?我可以在上传的同时添加 formobj - 如果可以,怎么做?
  2. How can I send multiple files?如何发送多个文件? formData.append("file", file); formData.append("文件", 文件); - this doesnt accept an array - 这不接受数组

Question 1 - Can I add formObj along with the upload - if so, how?问题 1 - 我可以在上传的同时添加 formObj - 如果可以,如何添加?

If you have to send the whole object in the formData there are 2 ways,如果你必须在 formData 中发送整个 object 有两种方式,

  1. Stringify the object like- formData.append("faqObj", JSON.stringify(faqObj));字符串化 object formData.append("faqObj", JSON.stringify(faqObj)); In this case, the server will have to parse the stringified object.在这种情况下,服务器必须解析字符串化的 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. 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])在这种情况下,服务器不必解析 object。

Question 2- How can I send multiple files?问题 2-如何发送多个文件? formData.append("file", file); formData.append("文件", 文件); - this doesnt accept an array - 这不接受数组

For this, you have to loop through the files array as follows为此,您必须按如下方式遍历文件数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM