在Angular6中发送多部分FormData的客户端补充

时间:2018-08-02 06:14:29

标签: http xmlhttprequest http-headers http-post angular6

“我的工作”要求我从ClientSide发送有关DTO的文件的其他信息。 我们将SpringBoot用作后端,将Angular6用作前端。

在ServerSide上:-

我在SpringBoot中制作了一个可以接受多部分数据的api。

    @PostMapping(value = "/multipartfiles",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
    @Timed
    public ResponseEntity<FileDTO> upload(@RequestPart FileDTO fileDTO,@RequestPart MultipartFile file) throws URISyntaxException {
        log.debug("REST request to save File And FileDescription");
        FileDTO result = fileService.save(fileDTO);
        if(result.getId()!=null){
            fileUploadService.storeFile(file,result.getId().toString()+FilenameUtils.getExtension(file.getOriginalFilename()));
        }
        return ResponseEntity.created(new URI("/api/multipartfiles/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);

    }

第一部分接受FileDTO,其中包含有关文件的详细信息,而其他部分接受正在上载的文件。

在客户端:-

我创建了一个页面,用户在其中填写文件的详细信息并上传文件。

<div class="row justify-content-center">
    <div class="col-8">
        <form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
            <h2>Upload a File</h2>
            <div>
                <div class="form-group">
                    <label class="form-control-label" for="field_fileName">File Name</label>
                    <input type="text" class="form-control" name="fileName" id="field_fileName"
                        [(ngModel)]="file.fileName" />
                </div>
                <div class="form-group">
                    <label class="form-control-label" for="field_description">Description</label>
                    <input type="text" class="form-control" name="description" id="field_description"
                        [(ngModel)]="file.description" />
                </div>
                <div class="form-group">
                    <label class="form-control-label" for="field_departmentName">Department Name</label>
                    <input type="text" class="form-control" name="departmentName" id="field_departmentName"
                        [(ngModel)]="file.departmentName" />
                </div>
                <div class="form-group">
                    <label class="form-control-label" for="field_entryDate">Entry Date</label>
                    <div class="d-flex">
                        <input id="field_entryDate" type="datetime-local" class="form-control" name="entryDate" [(ngModel)]="entryDate"
                        />
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-control-label" for="field_userEmail">User Email</label>
                    <input type="text" class="form-control" name="userEmail" id="field_userEmail"
                        [(ngModel)]="file.userEmail" />
                </div>
                <div class="form-group">
                    <label class="form-control-label" for="field_tag">Tag</label>
                    <input type="text" class="form-control" name="tag" id="field_tag"
                        [(ngModel)]="file.tag" />
                </div>

                <div class="form-group">
                    <label class="form-control-label" for="fileUpload">Choose File</label>
                    <input type="file" class="form-control" name="fileUpload" id="fileUpload"
                           [(ngModel)]="fileUpload" />
                </div>


            </div>
            <div>
                <button type="button" id="cancel-save" class="btn btn-secondary"  (click)="previousState()">
                    <fa-icon [icon]="'ban'"></fa-icon>&nbsp;<span>Cancel</span>
                </button>
                <button type="submit" id="save-entity" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">
                    <fa-icon [icon]="'save'"></fa-icon>&nbsp;<span>Save</span>
                </button>
            </div>
        </form>
    </div>
</div>

以及将详细信息和文件发布到服务器的组件和服务。 如下:-

组件:-

export class FileUploadComponent implements OnInit {
    private _file: FileModel;
    fileUpload:File;
    isSaving: boolean;
    entryDate: string;

    constructor(private fileService: FileService, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({ file }) => {
            this.file = file;
        });
    }

    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        this.file.entryDate = moment(this.entryDate, DATE_TIME_FORMAT);
this.subscribeToSaveResponse(this.fileService.uploadFormData(this.file,this.fileUpload));
    }


    private subscribeToSaveResponse(result: Observable<HttpResponse<FileModel>>) {
        result.subscribe((res: HttpResponse<FileModel>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    private onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    private onSaveError() {
        this.isSaving = false;
    }
    get file() {
        return this._file;
    }

    set file(file: FileModel) {
        this._file = file;
        this.entryDate = moment(file.entryDate).format(DATE_TIME_FORMAT);
    }
}

服务:-

export class FileService {
    private fileUploadUrl = SERVER_API_URL + 'api/multipartfiles';
    constructor(private http: HttpClient) {}
uploadFormData(fileDTO: FileModel,file:File): Observable<EntityResponseType>{
    const copy = this.convertDateFromClient(fileDTO);
    const toUpload=file;
    let  formData= new FormData();
    formData.append('fileDTO',copy);
    formData.append('file',toUpload);
    return this.http
        .post<FileModel>(this.fileUploadUrl,formData , { observe: 'response' })
        .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}

private convertDateFromClient(file: FileModel): FileModel {
    const copy: FileModel = Object.assign({}, file, {
        entryDate: file.entryDate != null && file.entryDate.isValid() ? file.entryDate.toJSON() : null
    });
    return copy;
}

private convertDateFromServer(res: EntityResponseType): EntityResponseType {
    res.body.entryDate = res.body.entryDate != null ? moment(res.body.entryDate) : null;
    return res;
}
}

哪个抛出错误: FileModel类型的参数不能分配给'string |类型的参数。斑点”。

我尝试先将其转换为FormData,然后尝试附加它。

let fileModel = new FormData();
        for (let copyKey in copy) {
            fileModel.append(copyKey,copy[copyKey]);
        }
        formData.append('fileDTO',fileModel);

这也会引发错误:- FormData类型的参数不能分配给'string |类型的参数。斑点”。

我无法在客户端中实现此api。

我尝试在requestParams中以dto形式在requestboy中发送文件,并更改了对我也不起作用的api。

任何人都可以在Angular6中实现此api还是为我建议针对此问题的不同解决方案。

0 个答案:

没有答案