0

I have an issue in my project. I've searched every related posts but couldn't find where is the problem. I would be grateful if anyone can help me. I'm trying to receive the response in my client side and handle it but when I get response it shows the Server Side URL with the raw text in the browser. Here is my Angular (app.component.ts) code:

import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { GetSipIdService } from './app.service';

const URL = 'http://localhost:8990/getId';

@Component({
  selector: 'app-root',
  providers: [ GetSipIdService ],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private getSipIdService: GetSipIdService,
  private http: HttpClient
  ) { }



  onSubmit(id: string, file: File) {
    const frmData = new FormData();
    frmData.append('id', id);
    frmData.append('inputPackage', file);
    this.http.post(URL, frmData ).subscribe( res => alert(res.toString() 
  ));

  }
}

and this is the HTML file :

<section class="login-block">
  <div class="container">
    <div class="row">
      <div class="col-md-4 login-sec">
        <form  >
        <!--<form action="http://localhost:8990/getId" method="POST" enctype="multipart/form-data">-->
          <label for="id">Id:</label>
          <input #id type="text" name="id" id="id" (change)="insertId($event)"  /><br/><br/>
          <div class="form-group files color">
            <label>Upload Your File </label>
            <input #inputPackage type="file" name="inputPackage" (change)="insertFile($event)" required class="file-controller" multiple="">
          </div>
          <div class="align-center">
            <input type="submit" class="btn btn-lg btn-info " value="Send the request" (click)="onSubmit(id.value, inputPackage)"/>
          </div>
        </form>
      </div>
      <div class="col-md-8 banner-sec">
        <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
          <div class="carousel-inner" role="listbox">
            <div class="carousel-item">
              <img class="d-block img-fluid" src="../images/test.jpg" alt="Test photo">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

On server Side I have this section :

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;



@Controller
public class GetSipIdController {  

    @CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
    @RequestMapping(method = RequestMethod.POST, value = "/getId", headers = {"content-type=multipart/mixed","content-type=multipart/form-data"})
    @ResponseBody
    String Response(@RequestParam("inputPackage") MultipartFile[] inputPackages, @RequestParam("id") String id) {

        String response = null;

       try {

            if (inputPackages != null && id != null && inputPackages.length > 0 && id.length() > 1) {
                 if (inputPackages[0].getOriginalFilename() != null ) {
                    if( inputPackages[0].getOriginalFilename().contains(".zip")) {
                        System.out.println("Input Package Name : " + inputPackages[0].getOriginalFilename());
                        System.out.println("Input Package Size : " + inputPackages[0].getSize());
                       // save file

                        userId = GetUserId.runProcess(recvPackage, id); 
                        response =  userId ;
                    }else{
                        System.out.println("==============>>>>>>>> The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!");
                        response = "The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!";
                    }
                }
            }else{
                System.out.println("==============>>>>>>>> The ID and valid zip file should be provide!");
                response = "The ID and valid zip file should be provide!";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}

And this is the image from response, it redirect to server url with raw response:

enter image description here

Far Zad
  • 389
  • 4
  • 11

2 Answers2

0

Please make below changes in controller method to work.You are sending response multipart/mixed type..

    @CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
    @PostMapping(value = "/getId")
    public String Response(@RequestParam("inputPackage") MultipartFile[] inputPackages, @RequestParam("id") String id) {

        String response = null;

        try {

            if (inputPackages != null && id != null && inputPackages.length > 0 && id.length() > 1) {
                if (inputPackages[0].getOriginalFilename() != null ) {
                    if( inputPackages[0].getOriginalFilename().contains(".zip")) {
                        System.out.println("Input Package Name : " + inputPackages[0].getOriginalFilename());
                        System.out.println("Input Package Size : " + inputPackages[0].getSize());
                        // save file

                        userId = GetUserId.runProcess(recvPackage, id);
                        response =  userId ;
                    }else{
                        System.out.println("==============>>>>>>>> The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!");
                        response = "The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!";
                    }
                }
            }else{
                System.out.println("==============>>>>>>>> The ID and valid zip file should be provide!");
                response = "The ID and valid zip file should be provide!";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
kj007
  • 6,073
  • 4
  • 29
  • 47
  • Thanks @kj007, I've done what you mention but right now again it redirected to the server URL but without response at this time. I mean the difference is there is no raw response in browser now an it shows this : Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. There was an unexpected error (type=Not Found, status=404). No message available – Far Zad Sep 24 '18 at 21:30
  • And when I only remove `headers = {"content-type=multipart/mixed","content-type=multipart/form-data"}` the result is same as before. I mean redirect to server URL and shows raw response – Far Zad Sep 24 '18 at 21:31
0

I finally got the point. First remove the <form> from HTML, then changed my Angular into this :

import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

const URL = 'http://localhost:8990/getUserId'; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(
  private http: HttpClient
  ) { }

   fileToUpload: File = null; 
   id: String = '0'; 

   inputId(event) { 
    this.id= event.target.value; 
    console.log('id is -- > ' + event.target.value ); 
   } 
   inputFile(event) {
    this.fileToUpload = event.target.files[0];
    console.log('File path -- > ' + event.target.files[0].name );
  } 
  onSubmit(id: string, file: File) {
    event.preventDefault();
    const frmData = new FormData();
    console.log('POST');
    // @ts-ignore
    frmData.append('id', this.id);
    frmData.append('inputPackage', this.fileToUpload);
    console.log('id --> ' + this.id);
    console.log('File name --> ' + this.fileToUpload.name);
    this.http.post(URL, frmData ).subscribe( res => console.log('--==>> ' + JSON.stringify(res ))); 
  }
}

and change my Spring response to JSON format which make easier to receive from Angular.

used this as a convert class.

Far Zad
  • 389
  • 4
  • 11