0
votes

I am using ngprime fileupload from here to upload file and send it to a rest service which validates swagger json and then save file content to db but facing issues while uploading file.

here is my fileupload.html

<div class="ui-g">
 <p-growl [value]="msgs"></p-growl>
 <form [formGroup]="uploadForm" novalidate>
<div class="ui-g-12">
  <div class="ui-grid-row">
    <div class="ui-grid-col-12" [ngClass]="{'has-error':!uploadForm.controls['activity'].valid && uploadForm.controls['activity'].touched}">
      <div class="ui-grid-col-2"><label>Product Name </label></div>
      <div class="ui-grid-col-8">
        <input class="inputtext" type="text" formControlName="activity" placeholder="Product Activity"/>
        <div *ngIf="uploadForm.controls['activity'].hasError('required') && uploadForm.controls['activity'].touched" class="alert alert-danger">You must enter Product Name.</div>
      </div>
    </div>
  </div>
</div>
<div class="ui-g-12" >
  <p-fileUpload name="demo[]" url="{{uploadUrl}}" (onUpload)="onUpload($event)" accept=".json,.text,.yml" maxFileSize="1000000" [disabled]="!uploadForm.valid">
    <template pTemplate="content">
      <ul *ngIf="uploadedFiles.length">
        <li *ngFor="let file of uploadedFiles">{{file.name}} - {{file.size}} bytes</li>
      </ul>
    </template>
  </p-fileUpload>
</div>

and upload.html view

I am getting ... XMLHttpRequest cannot load http://localhost:8080/upload. Response for preflight is invalid (redirect) error. Actually the request not even going to my rest serevice which I am running locally ...

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity uploadFile(MultipartHttpServletRequest request, HttpServletResponse response, HttpServletRequest httpRequest) {
   /swagger validation logic 
}

what's the issue in my code?

2
Basically file upload should be MultipartFile MediaType.MULTIPART_FORM_DATA_VALUE - Karthigeyan Vellasamy
It worked for Angular1.4 where I did same http.post(url, file) , is there anyway to upload json or text files? - user1653027

2 Answers

0
votes

Use the following REST endpoint that consume the file being uploaded and create JSON response

@RequestMapping(value = "/upload", 
    method = RequestMethod.POST, 
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public @ResponseBody ResponseEntity uploadFile(@RequestParam("myfile") MultipartFile file, String fileName) throws IllegalStateException, IOException {
         /swagger validation logic  
      }

Here "myfile" refers to the name attribute given in component.

0
votes

Well I am using Jersey and below is my working code for primeng file upload (angular 4)

HTML Code

<div class="row header">
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>
    <div class="col-xs-1">&nbsp;</div>

    <div class="col-xs-3">
    <p>
  owner-shop-customization works!
  <p-fileUpload name="file" url="http://localhost:1006/jsflab/rest/OwnerMyShop/uploadShopLogo"></p-fileUpload>
</p>
    </div>
</div>

TS

import { Component, OnInit } from '@angular/core';
import {FileUploadModule} from 'primeng/primeng';

@Component({
  selector: 'app-owner-shop-customization',
  templateUrl: './owner-shop-customization.component.html',
  styleUrls: ['./owner-shop-customization.component.css']
})
export class OwnerShopCustomizationComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

Webservice

@POST
    @Path("/uploadShopLogo")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response uploadPdfFile(  @FormDataParam("file") InputStream fileInputStream,
                                    @FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
    {  
            String fileLocation = "C://" + fileMetaData.getFileName();  
                    //saving file  
            try {  
                FileOutputStream out = new FileOutputStream(new File(fileLocation));  
                int read = 0;  
                byte[] bytes = new byte[1024];  
                out = new FileOutputStream(new File(fileLocation));  
                while ((read = fileInputStream.read(bytes)) != -1) {  
                    out.write(bytes, 0, read);  
                }  
                out.flush();  
                out.close();  
            } catch (IOException e) {e.printStackTrace();}  
            String output = "File successfully uploaded to : " + fileLocation;  
            return Response.status(200).entity(output).build();  
        }  

web.xml

 <servlet> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
      <init-param> 
         <param-name>jersey.config.server.provider.packages</param-name> 
         <param-value>invoicegeneratorwebservice</param-value> 
      </init-param> 
       <init-param>  
    <param-name>jersey.config.server.provider.classnames</param-name>  
    <param-value>org.glassfish.jersey.filter.LoggingFilter;  
     org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>  
</init-param>  
    <load-on-startup>1</load-on-startup>
   </servlet> 
   <servlet-mapping> 
      <servlet-name>Jersey RESTful Application</servlet-name> 
      <url-pattern>/rest/*</url-pattern> 
   </servlet-mapping>   

pom.xml

<dependency>
    <groupId>org.glassfish.jersey.bundles</groupId>
    <artifactId>jaxrs-ri</artifactId>
    <version>2.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.25.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.17</version>
</dependency>