2

I am stuck in getting the request at my REST Controller. Below is my Controller method :

@RestController
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders = "*")
public class UserController {

@Autowired
    public UserService userService;

    @PostMapping(value = "/fileUploadApi",  consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public @ResponseBody StatusUpload fileUpload(@RequestPart("uploadfile") MultipartFile file, @RequestPart("user") User userDto) throws Exception{
        StatusUpload status= new StatusUpload();
        status = userService.callUserServiceForFileRead(file, userDto);
        return status;
    }

In ApplicationConfig.java, I added the following :

@Bean
     public MultipartResolver multipartResolver() {
         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
         multipartResolver.setMaxUploadSize(500000000);
         return multipartResolver;
     }

Below is the code I have written for file upload at Angular5 end:

HTML:

    <!-- Other form elements -->
    <!-- Used PrimeNG Custom Upload Handler to get the File Object https://www.primefaces.org/primeng/#/fileupload -->
        <label>Upload template </label>
          <p-fileUpload (uploadHandler)="getFile($event)" auto="true" customUpload="true"  accept=".xlsx,application/msexcel"  previewWidth="0" [showUploadButton]="false" [showCancelButton]="false">
          </p-fileUpload>
<!-- Form Submit Button -->
<button type="button" (click)="submit()">SUBMIT</button>

COMPONENT :

    user: User = new User;
// Set other form element data in user object.
    uploadFile: File;
    getFile(event) {
        this.uploadfile= event.files[0];
      }
submit() {
    this.userService.saveUserData(this.user,this.uploadFile);

  }

SERVICE :

options = {
    headers: new HttpHeaders({  'Content-Type': ''  })
  };
constructor(private http: HttpClient) { }
    saveUserData(user:User, uploadFile:File){
    var formData: FormData = new FormData();
    formData.append('user',JSON.stringify(user));
    formData.append('uploadfile',uploadFile);
    return this.http.post<StatusUpload>(baseUrl + "/fileUploadApi", formData, this.options);
    }

When I use the above Service, it gives me no response/no Exception don't know why. The request even didn't reach my RESTController. I read a different approach in some post & used it as below :

saveUserData(user: User, uploadFile: File) {
var formData: FormData = new FormData();
Observable.fromPromise(new Promise((resolve, reject) => {
  let xhr = new XMLHttpRequest();
  formData.append('user', new Blob([JSON.stringify(user)],
    {
      type: "application/json"
    }));
  formData.append('uploadfile', uploadFile);
  xhr.open("POST", baseUrl + "/fileUploadApi", true);
  xhr.send(formData);
}));
}

With above, I get org.springframework.web.multipart.support.MissingServletRequestPartException.

Can anyone please help to get this code working. I need to use the http.post() in my Angular service, not the XMLHttpRequest.send() one.

Random Guy
  • 51
  • 3
  • 12

1 Answers1

0

You need to subscribe to the observable.

An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.

Docs

abrandell
  • 63
  • 4
  • I can't believe I made this mistake.. Thanks for identifying it.. It then says, Content Type cannot be ' ', HttpMediaTypeNotSupportedException.. Can you please help what exactly should be the Content Type for the HTTP post here. – Random Guy Nov 06 '18 at 09:58
  • application/json gives org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported... If I remove the Content Type as suggested here : https://stackoverflow.com/questions/36005436/the-request-was-rejected-because-no-multipart-boundary-was-found-in-springboot , it gives org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'uploadfile' is not present.. – Random Guy Nov 06 '18 at 10:42
  • 'Content-Type': 'multipart/form-data' gives org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found – Random Guy Nov 06 '18 at 10:46