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