在iris框架中结合mysql保存上传文件路径,核心做法是调用 c.formfile() 获取文件句柄,使用 file.save() 将文件持久化到磁盘或对象存储,并将生成的唯一文件名或路径存入数据库。具体实现时,需确保数据库连接池已初始化,并在事务中执行插入操作以保障数据一致性。若未对上传目录进行权限配置或数据库字段类型不匹配(如长度不足),会导致写入失败。
FormFile() 处理多文件上传并返回结构体
该函数用于解析 multipart/form-data 请求,直接提取文件流和元数据。它支持单文件和多文件模式,开发者可通过指定键名获取对应的 *multipart.FileHeader 对象。若请求体不符合规范或键名不存在,函数会返回错误,此时应检查 Content-Type 是否包含 boundary 参数。

package main
import (
"fmt"
"log"
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
app.Post("/upload", func(c iris.Context) {
// 获取单个文件
file, header, err := c.FormFile("avatar")
if err != nil {
c.StatusCode(iris.StatusBadRequest)
c.WriteString("Failed to get file: " + err.Error())
return
}
defer file.Close()
fmt.Printf("Filename: %s, Size: %d\n", header.Filename, header.Size)
c.WriteString("File received successfully")
})
app.Listen(":8080")
}使用 file.Save() 安全持久化文件至本地
Iris 提供了便捷的 file.Save() 方法,可将内存中的文件头直接保存到指定路径。该方法会自动创建父目录(若存在)并处理重名冲突(默认覆盖)。在实际项目中,建议生成 UUID 作为新文件名以避免冲突,并验证文件扩展名以限制上传类型。保存成功后,返回的路径字符串可直接用于后续数据库插入。
安装、修复、更新或打包一个基于 Python 和 PyMySQL 实现的 Windows `mysql` 命令。适用于用户希望在 PowerShell/CMD 中输入 `mysql` 时重定向到 Python 实现、需要交互式输入 MySQL 连接信息、需要同步到当前用户本地 bin 目录,或需要将该能力封装成可公开复用的 Codex skill。

package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/kataras/iris/v12"
"github.com/google/uuid"
)
func main() {
app := iris.New()
// 确保上传目录存在
uploadDir := "./uploads"
if err := os.MkdirAll(uploadDir, 0755); err != nil {
log.Fatal(err)
}
app.Post("/save-file", func(c iris.Context) {
file, _, err := c.FormFile("document")
if err != nil {
c.StatusCode(iris.StatusBadRequest)
c.WriteString(err.Error())
return
}
defer file.Close()
// 生成唯一文件名
newFileName := uuid.New().String() + filepath.Ext(file.Filename)
destPath := filepath.Join(uploadDir, newFileName)
// 保存文件
if err := file.Save(destPath); err != nil {
c.StatusCode(iris.StatusInternalServerError)
c.WriteString("Save failed: " + err.Error())
return
}
c.JSON(iris.Map{
"status": "success",
"path": destPath,
})
})
app.Listen(":8080")
}基于事务的 MySQL 路径记录与异常回滚
当文件保存成功后,必须将其路径记录到 MySQL 数据库中。由于涉及 I/O 操作和数据库写入两个独立步骤,建议使用 SQL 事务来保证原子性:要么文件路径入库成功,要么全部回滚。若数据库连接断开或约束违反(如外键错误),事务回滚可防止产生孤立的数据记录。此外,需注意 MySQL 表中存储路径的字段类型应为 VARCHAR 或 TEXT,并根据实际路径长度设置合适的大小。
package main
import (
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
"github.com/kataras/iris/v12"
_ "github.com/go-sql-driver/mysql"
"github.com/google/uuid"
)
var db *sql.DB
func initDB() {
var err error
db, err = sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/mydb?parseTime=True")
if err != nil {
log.Fatal(err)
}
if err = db.Ping(); err != nil {
log.Fatal(err)
}
}
func main() {
initDB()
app := iris.New()
uploadDir := "./uploads"
os.MkdirAll(uploadDir, 0755)
app.Post("/upload-with-db", func(c iris.Context) {
file, _, err := c.FormFile("image")
if err != nil {
c.StatusCode(iris.StatusBadRequest)
c.WriteString(err.Error())
return
}
defer file.Close()
newFileName := uuid.New().String() + filepath.Ext(file.Filename)
destPath := filepath.Join(uploadDir, newFileName)
if err := file.Save(destPath); err != nil {
c.StatusCode(iris.StatusInternalServerError)
c.WriteString("Save failed")
return
}
// 开启事务
tx, err := db.Begin()
if err != nil {
c.StatusCode(iris.StatusInternalServerError)
c.WriteString("DB transaction start failed")
return
}
defer tx.Rollback() // 确保在发生错误时回滚
// 假设表结构为 files (id INT AUTO_INCREMENT, path VARCHAR(255))
stmt, err := tx.Prepare("INSERT INTO files (path) VALUES (?)")
if err != nil {
c.StatusCode(iris.StatusInternalServerError)
c.WriteString("Prepare failed")
return
}
defer stmt.Close()
_, err = stmt.Exec(destPath)
if err != nil {
c.StatusCode(iris.StatusInternalServerError)
c.WriteString("Insert failed")
return
}
if err = tx.Commit(); err != nil {
c.StatusCode(iris.StatusInternalServerError)
c.WriteString("Commit failed")
return
}
c.JSON(iris.Map{
"status": "saved",
"path": destPath,
})
})
app.Listen(":8080")
}

















