使用Angular5将图像和表单字段发送到API

时间:2019-05-10 15:17:54

标签: angular laravel image

我有一个包含2个字段和1个图像字段的表单。

    public frontImageFile : File;

    selectFrontImage(event: any): void{
     if(event.target.files[0]) {      
        this.frontImageFile = event.target.files[0];
     } 
    }

    newCardForm = new FormGroup({
        first_name: new FormControl('')),
        email: new FormControl(''),
        image: new FormControl(''),
    });

    const cardData = new FormData();
    cardData.append('frontImage', this.frontImageFile, this.frontImageFile.name);
    const data = {
        first_name: this.newCardForm.value.first_name,
        email: this.newCardForm.value.email,
        image :cardData, 
    }

我试图通过一个API调用来发送所有3个字段的信息。

我的服务

    saveStoreCard(data) {
    let headers = new Headers();
        headers.append("Authorization", "Bearer " + sessionStorage.token);
        headers.set("content-type", "application/json");
        headers.append("accept", "application/json");
        let options = new RequestOptions({
            headers: headers
        });

        return this.http
            .post(`${this.SERVER_HOST}saveStoreCard`, data, options)
            .pipe(
                tap(
                    response => {   return response; },
                    error => {  this.loggedOutSet(error); }
                )
            );
    }

当我在服务器端发送图像其调整Null时。

1 个答案:

答案 0 :(得分:1)

您的代码在这里有问题

import matplotlib.pyplot as plt

name = ['A', 'B', 'C'] 
score = [2,4,6] 

# Set color for every score
color = ['green' if x>3 else 'red' for x in score]

# Create scatter plot
fig, ax = plt.subplots()
ax.scatter(name, score, c=color)

# Set label for every score inside scatter plot
for i, n in enumerate(name):
    ax.annotate(n, (n,score[i]))

plt.show()

如果发送FormData,则必须使用FormData格式化所有数据,因此必须像这样更改代码

const cardData = new FormData();
cardData.append('frontImage', this.frontImageFile, this.frontImageFile.name);
const data = {
  first_name: this.newCardForm.value.first_name,
  email: this.newCardForm.value.email,
  image : cardData, 
}

让我知道您是否仍然有任何问题