Gorm在使用表单数据文件上传时出现创建错误。

huangapple go评论115阅读模式
英文:

Gorm Create Error with Form-Data File Upload

问题

我正在尝试在PostgreSQL服务器中创建一条记录。请求以多部分格式的文件数据发送给我。在将文件上传到我的端点后,我调用gorm.Create,但它抛出了一个错误。

当我注释掉文件上传部分时,错误消失了,但我需要上传文件。

这是我的控制器部分:

func (pc ProductController) Create(c *gin.Context) {

	var product migrations.Product

	if err := c.Bind(&product); err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "İşlem başarısız. Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-01"})
		return
	}

	if product.Name == "" {
		c.JSON(400, gin.H{"error": "Name is required", "message": "İşlem başarısız. Lütfen Ad Alanını Boş Bırakmayınız. Hata kodu: PD-CRT-02"})
		return
	}

	if product.Price == 0 {
		c.JSON(400, gin.H{"error": "Price is required", "message": "İşlem başarısız. Lütfen Fiş Değeri Alanını Boş Bırakmayınız. Hata kodu: PD-CRT-03"})
		return
	}
	if product.ID != 0 {
		c.JSON(400, gin.H{"error": "Remove ID field", "message": "Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-ID-01"})
		return
	}

	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "Lütfen Resim Ekleyiniz. Hata kodu: PD-CRT-IMG-01"})
	}
	fileName := time.Now().Format("20060102150405") + "-" + strings.Split(file.Filename, ".")[0] + "." + strings.Split(file.Filename, ".")[1]
	dst := fmt.Sprintf("./public/images/%s", fileName)
	err = c.SaveUploadedFile(file, dst)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-IMG-02"})
		return
	}

	product.Image = &migrations.File{
		Path:      fileName,
		Extension: strings.Split(file.Filename, ".")[1],
	}
	log.Println(product)
	err = db.Conn.Create(&product).Error
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "İşlem başarısız. Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-04"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "Ürün başarıyla eklendi.", "data": product})
	return
}

以及我的请求:

Gorm在使用表单数据文件上传时出现创建错误。

错误信息:

{
    "error": "strconv.ParseInt: parsing \"products\": invalid syntax; strconv.ParseInt: parsing \"products\": invalid syntax",
}

这是我的结构体:


type Order struct {
	ID         uint       `gorm:"primarykey" json:"id"`
	UserID     int        `gorm:"index" json:"user_id"`
	RoomNo     int        `gorm:"comment:oda_no" json:"room_no"`
	IsDone     bool       `gorm:"default:false" json:"is_done"`
	StatusCode int        `gorm:"default:0" json:"status_code"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
	DeletedAt  time.Time  `gorm:"index" json:"deleted_at"`
	Products   []*Product `gorm:"many2many:orders_products" json:"products,omitempty"`
}

type Product struct {
	ID        uint      `gorm:"primarykey" json:"id" form:"id"`
	Name      string    `gorm:"type:varchar(255)" json:"name" form:"name"`
	Price     float64   `gorm:"type:decimal(10,2)" json:"price" form:"price"`
	IsActive  bool      `gorm:"default:true" json:"is_active" form:"isActive"`
	Image     File      `gorm:"polymorphic:Module" json:"image,omitempty"`
	CreatedAt time.Time `json:"created_at" form:"createdAt"`
	UpdatedAt time.Time `json:"updated_at" form:"updatedAt"`
	DeletedAt time.Time `gorm:"index" json:"deleted_at"`
}

type OrdersProduct struct {
	OrderID   int `gorm:"index" json:"order_id"`
	ProductID int `gorm:"index" json:"product_id"`
	Count     int `gorm:"default:0" json:"count"`
}


type File struct {
	ID         uint      `gorm:"primarykey" json:"id"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	DeletedAt  time.Time `gorm:"index" json:"deleted_at"`
	Path       string    `gorm:"type:varchar(255)" json:"path"`
	Extension  string    `gorm:"type:varchar(255)" json:"extension"`
	ModuleID   int       `gorm:"type:integer" json:"module_id"`
	ModuleType int       `gorm:"type:integer" json:"module_type"`
}


英文:

I'm trying to create a record in a PostgreSQL server. The request comes to me as file data in multipart format. After uploading the file to my end, I call gorm.Create, but it throws an error.

When I comment out the file upload part, the error disappears, but I need to upload the file.

here is my controller part:

func (pc ProductController) Create(c *gin.Context) {

	var product migrations.Product

	if err := c.Bind(&product); err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "İşlem başarısız. Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-01"})
		return
	}

	if product.Name == "" {
		c.JSON(400, gin.H{"error": "Name is required", "message": "İşlem başarısız. Lütfen Ad Alanını Boş Bırakmayınız. Hata kodu: PD-CRT-02"})
		return
	}

	if product.Price == 0 {
		c.JSON(400, gin.H{"error": "Price is required", "message": "İşlem başarısız. Lütfen Fiş Değeri Alanını Boş Bırakmayınız. Hata kodu: PD-CRT-03"})
		return
	}
	if product.ID != 0 {
		c.JSON(400, gin.H{"error": "Remove ID field", "message": "Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-ID-01"})
		return
	}

	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "Lütfen Resim Ekleyiniz. Hata kodu: PD-CRT-IMG-01"})
	}
	fileName := time.Now().Format("20060102150405") + "-" + strings.Split(file.Filename, ".")[0] + "." + strings.Split(file.Filename, ".")[1]
	dst := fmt.Sprintf("./public/images/%s", fileName)
	err = c.SaveUploadedFile(file, dst)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-IMG-02"})
		return
	}

	product.Image = &migrations.File{
		Path:      fileName,
		Extension: strings.Split(file.Filename, ".")[1],
	}
	log.Println(product)
	err = db.Conn.Create(&product).Error
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error(), "message": "İşlem başarısız. Lütfen tekrar deneyiniz veya sistem yöneticinize başvurun. Hata kodu: PD-CRT-04"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "Ürün başarıyla eklendi.", "data": product})
	return
}

And my request:

Gorm在使用表单数据文件上传时出现创建错误。

The Error:

{
    "error": "strconv.ParseInt: parsing \"products\": invalid syntax; strconv.ParseInt: parsing \"products\": invalid syntax",
}

There are my structs:


type Order struct {
	ID         uint       `gorm:"primarykey" json:"id"`
	UserID     int        `gorm:"index" json:"user_id"`
	RoomNo     int        `gorm:"comment:oda_no" json:"room_no"`
	IsDone     bool       `gorm:"default:false" json:"is_done"`
	StatusCode int        `gorm:"default:0" json:"status_code"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`
	DeletedAt  time.Time  `gorm:"index" json:"deleted_at"`
	Products   []*Product `gorm:"many2many:orders_products" json:"products,omitempty"`
}

type Product struct {
	ID        uint      `gorm:"primarykey" json:"id" form:"id"`
	Name      string    `gorm:"type:varchar(255)" json:"name" form:"name"`
	Price     float64   `gorm:"type:decimal(10,2)" json:"price" form:"price"`
	IsActive  bool      `gorm:"default:true" json:"is_active" form:"isActive"`
	Image     File      `gorm:"polymorphic:Module" json:"image,omitempty"`
	CreatedAt time.Time `json:"created_at" form:"createdAt"`
	UpdatedAt time.Time `json:"updated_at" form:"updatedAt"`
	DeletedAt time.Time `gorm:"index" json:"deleted_at"`
}

type OrdersProduct struct {
	OrderID   int `gorm:"index" json:"order_id"`
	ProductID int `gorm:"index" json:"product_id"`
	Count     int `gorm:"default:0" json:"count"`
}


type File struct {
	ID         uint      `gorm:"primarykey" json:"id"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	DeletedAt  time.Time `gorm:"index" json:"deleted_at"`
	Path       string    `gorm:"type:varchar(255)" json:"path"`
	Extension  string    `gorm:"type:varchar(255)" json:"extension"`
	ModuleID   int       `gorm:"type:integer" json:"module_id"`
	ModuleType int       `gorm:"type:integer" json:"module_type"`
}


答案1

得分: 1

请检查File结构体的单元类型。strconv.ParseInt()函数将字符串转换为值。我认为ModuleID、ModuleType或两者都必须是字符串。

英文:

Check the File struct's unit types. strconv.ParseInt() converts strings to values. ModuleID, ModuleType or both have to be string i think.

huangapple
  • 本文由 发表于 2023年7月15日 01:53:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76690129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定