繁体   English   中英

我应该如何在Http POST请求的主体中发送图像文件以及其他形式的角度数据5。后端在Laravel中使用Intervention包

[英]How shall I send an image file in body of Http POST request in along with other form data angular 5. Backend is using Intervention package in Laravel

这是邮递员数据

这就是我试图实现的

    @ViewChild('imageUpload') elem: ElementRef;



fetchImage() : File{
    const Imagefiles = this.elem.nativeElement
    this.profileImagefile = Imagefiles.files[0];
    console.log("ProfileImage",this.profileImagefile)
    return this.ProfileImagefile;
}



addUser(createAgent: NgForm) {

const formData: FormData = new FormData(createAgent.value);
    formData.append("image", this.fetchImage(), this.fetchImage().name)
    console.log("formData",formData)

    console.log('formvalue', createProfile.value);
    this.httpService.createProfile(createProfile.value)
        .subscribe(....)

在httpService中

    createProfile(data: any) {
    return this.httpClient.post('agent/', data) }

后端使用的是PHP Laravel。 对于通过HTTP POST发送的表单数据,它将引发错误。 通过Postman可以发送数据,但不能从FrontEnd发送数据。这样做的正确方法是什么? 谢谢

我这样做是这样的:

uploadFile(fileType: FileType, file: File): Observable<string> {
    let formData: FormData = new FormData();
    formData.append('file', file);
    formData.append('name', file.name.substring(0, file.name.indexOf(".")));
    formData.append('extension', file.name.substring(file.name.indexOf(".") + 1, file.name.length));
    formData.append('fileType', fileType);
    return this.fileHttpHandler
        .uploadFile(formData)
        .map(response => response.json())
        .catch(error => this.restErrorHandler.handleRestError(error));
}

fileHttpHandler.uploadFile()看起来像这样:

public uploadFile(formData: FormData): Observable<Response> {
    return this.http.post(this.restApiUtilsService.getUrl(this.FILES_API_PATH) + "/save",
        formData, this.restApiUtilsService.getMultipartAuthHeaders());
}

在标头中,您无需指定诸如multipart之类的任何内容-它是自动完成的。 我在那里传递身份验证令牌,这就是为什么有“ getMultipartAuthHeaders”的原因。 只是根本不要在标头中指定Content-Type。

通过首先获取所有ngForm数据并将其附加到表单数据中,然后将图像文件附加到相同的表单数据中,我解决了该问题。 用于for-in循环以获取ngForm数据。

        addUser(createAgent: NgForm) {                                     
        const formData: FormData = new FormData();
        for( let val in createAgent.value  ){
            formData.append(val, createAgent.value[val])
            console.log(val, createAgent.value[val])
        }
        formData.append("image", this.fetchImage(), this.fetchImage().name);
        console.log("formData",formData)
    }

然后将此表单数据发送到后端

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM