簡體   English   中英

將對象內部的文件從angular2發送到Spring Rest

[英]Sending File inside object from angular2 to Spring Rest

嗨,這個問題不是新問題,但是我找不到任何合適的方法。請幫助我。

需求

在json對象中發送上傳的文件,並在靜態服務中處理。

示例json的示例:

{
    id:"123",
    name:"XYZ",
    nonProfit:[{
        name:"profile1",
        attachedFile: object of file
    }, {
        name:"profile2",
        attachedFile: object of file2
    }]
}

問題:

我可以在json中獲取文件對象,但由於我認為有效負載沒有正確地傳遞到Web服務,因此無法發送至該服務。

有什么方法可以發送如下所示的json並在后端服務中處理。

首先,您必須獲取文件的base64

 public readFile(fileToRead: File): Observable<MSBaseReader>{
        let base64Observable = new ReplaySubject<MSBaseReader>(1);

        let fileReader = new FileReader();
        fileReader.onload = event => {
             base64Observable.next(fileReader.result);
        };
        fileReader.readAsDataURL(fileToRead);

        return base64Observable;
}

讀取base64后,您應該將其傳遞給json文件

let params = {
            id:"123",
            name:"XYZ",
            nonProfit:[{
            name:"profile1",
            attachedFile: this.fileBase64
}

之后,您可以創建服務以將數據發送到后端。首先,為調用api創建一個server.service.ts文件

import {Injectable} from '@angular/core';
import {Headers, Http, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/toPromise';
import {AuthenticationService} from "./authentication.service";
import {isUndefined} from "util";

@Injectable()
export class ServerService {
     constructor(private http: Http) {
     }

     servicePost(service: string, parameters: string) {
           return this.http.post('/service/' + service, parameters)
     }
}

將您的服務添加到模塊的提供者

@NgModule({
declarations: [...],
imports: [...],
providers: [AuthGuard,
    ServerService],
entryComponents: [...],
bootstrap: [AppComponent]
})
export class AppModule {
}

現在將您的服務添加到構造函數中

constructor(private serverService: ServerService) {
}

並在組件中調用您的服務。

this.service.servicePost('subDirectoryOfService',params).subscribe(data=>{dosomething after call api})

現在在后端,您將獲得以下路徑的/service/subDirectoryOfService/service/subDirectoryOfService

在控制器中,您使用此方法

@RequestMapping('/service/subDirectoryOfService')
public String subDirectoyOfService(@FormParam String params){
      JSONObject json = new JSONObject(params);
      String base64 = json.getString("attachedFile");
      System.out.println("base64 of file: "+ base64);
      return "{\"res\":\"success\"}"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM