在Go语言中使用GORM实现MySQL存储图片可以通过以下步骤实现:
type Image struct { ID uint Name string Path string Size int64 }
db.AutoMigrate(&Image{}) db.Model(&Image{}).AddUniqueIndex("idx_image_path", "path")
func SaveImageToDB(db *gorm.DB, name string, path string, size int64) error { image := Image{Name: name, Path: path, Size: size} err := db.Create(&image).Error if err != nil { return err } // Save the image file to local file system // You can use ioutil.WriteFile() or other methods to save the image file return nil }
name := "example.jpg" path := "/path/to/example.jpg" size := 1024 // example size err := SaveImageToDB(db, name, path, size) if err != nil { log.Fatalf("Failed to save image to database: %v", err) }
通过以上步骤,你可以使用GORM在MySQL数据库中存储图片,并保存图片到本地文件系统。需要注意的是,为了避免数据库存储大量的图片数据,建议只保存图片的路径和其他相关信息到数据库中,而将图片文件保存到本地文件系统。