使用Golang的Gofiber框架通过API发送文件的方法

使用Golang的Gofiber框架通过API发送文件的方法 晚上好,团队。我想知道是否可以使用下面提到的 gofiber 模块发送文件。

使用 POST 方法,MultipartFormData。

图片

gofiber/fiber

⚡️ 受 Express 启发,用 Go 编写的 Web 框架。通过在 GitHub 上创建账户来为 gofiber/fiber 的开发做出贡献。


更多关于使用Golang的Gofiber框架通过API发送文件的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于使用Golang的Gofiber框架通过API发送文件的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Gofiber框架中通过API发送文件可以通过MultipartFormData实现。以下是具体实现方法:

package main

import (
    "fmt"
    "log"
    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    // 处理文件上传的POST端点
    app.Post("/upload", func(c *fiber.Ctx) error {
        // 解析multipart/form-data
        form, err := c.MultipartForm()
        if err != nil {
            return c.Status(fiber.StatusBadRequest).SendString("无法解析表单数据")
        }

        // 获取上传的文件
        files := form.File["file"]
        if len(files) == 0 {
            return c.Status(fiber.StatusBadRequest).SendString("未找到文件")
        }

        // 处理每个上传的文件
        for _, file := range files {
            // 保存文件到服务器
            err := c.SaveFile(file, "./uploads/"+file.Filename)
            if err != nil {
                return c.Status(fiber.StatusInternalServerError).
                    SendString(fmt.Sprintf("保存文件失败: %v", err))
            }
        }

        return c.JSON(fiber.Map{
            "message": "文件上传成功",
            "count":   len(files),
        })
    })

    // 处理文件下载的GET端点
    app.Get("/download/:filename", func(c *fiber.Ctx) error {
        filename := c.Params("filename")
        return c.Download("./uploads/" + filename)
    })

    log.Fatal(app.Listen(":3000"))
}

对于发送文件到客户端,可以使用以下方法:

// 方法1:直接发送文件
app.Get("/send-file", func(c *fiber.Ctx) error {
    return c.SendFile("./uploads/example.pdf")
})

// 方法2:发送文件并设置自定义文件名
app.Get("/send-file-custom", func(c *fiber.Ctx) error {
    return c.SendFile("./uploads/example.pdf", "custom-name.pdf")
})

// 方法3:使用Attachment设置下载头
app.Get("/attachment", func(c *fiber.Ctx) error {
    c.Attachment("./uploads/example.pdf", "download.pdf")
    return c.SendFile("./uploads/example.pdf")
})

// 方法4:流式传输大文件
app.Get("/stream-file", func(c *fiber.Ctx) error {
    return c.SendStream("./uploads/large-video.mp4")
})

如果需要通过POST请求发送文件到其他服务:

import (
    "bytes"
    "mime/multipart"
    "net/http"
    "os"
)

func sendFileToExternalAPI(filename string, targetURL string) error {
    // 打开文件
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    // 创建multipart writer
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    
    // 创建文件字段
    part, err := writer.CreateFormFile("file", filename)
    if err != nil {
        return err
    }
    
    // 复制文件内容
    _, err = io.Copy(part, file)
    if err != nil {
        return err
    }
    
    writer.Close()

    // 发送请求
    req, err := http.NewRequest("POST", targetURL, body)
    if err != nil {
        return err
    }
    
    req.Header.Set("Content-Type", writer.FormDataContentType())
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    return nil
}

这些示例展示了在Gofiber框架中通过API发送和接收文件的基本方法。

回到顶部