将Angular 6中的剩余发布响应作为客户端处理,将Spring Boot作为服务器API处理

时间:2018-09-24 00:01:12

标签: rest api spring-boot post angular6

我的项目有问题。我搜索了所有相关帖子,但找不到问题所在。如果有人可以帮助我,我将不胜感激。 我正在尝试在客户端接收响应并进行处理,但是当我获得响应时,它会在浏览器中显示带有原始文本的服务器端URL。 这是我的Angular(app.component.ts)代码:

word = 'abc'

for line in open('file.txt').readlines():
    if word in line:
        return True

这是HTML文件:

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() 
  ));

  }
}

在服务器端,我有此部分:

<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>

这是响应的图像,它使用原始响应重定向到服务器url:

enter image description here

2 个答案:

答案 0 :(得分:0)

请在控制器方法上进行以下更改以起作用。您正在发送响应多部分/混合类型。

    @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;
    }

答案 1 :(得分:0)

我终于明白了。 首先从HTML中删除<form>,然后将Angular更改为此:

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 ))); 
  }
}

并将Spring响应更改为JSON格式,从而更容易从Angular接收。

this用作转换类。