duanshaiduhao2471 2019-07-08 14:14
浏览 1766
已采纳

如何在Golang中将multipart.File类型转换为* os.File

I am trying to upload video to CloudFlare, but in docs they use os.Open but in my situation user uploads file via html form

Golang CloudFlare Docs: https://developers.cloudflare.com/stream/getting-started/uploading-golang/

file, err := c.FormFile("file")
if err != nil {
    log.Errorf("get file error: %s", err)
    return c.JSONStatus(http.StatusBadRequest)
}

sourceFile, err := file.Open()
if err != nil {
    log.Errorf("open file error: %s", err)
    return c.JSONStatus(http.StatusInternalServerError)
}

headers := make(http.Header)
headers.Add("X-Auth-Email", "***")
headers.Add("X-Auth-Key", "***")

config := &tus.Config{
    ChunkSize:           5 * 1024 * 1024, // Cloudflare Stream requires a minimum chunk size of 5MB.
    Resume:              false,
    OverridePatchMethod: false,
    Store:               nil,
    Header:              headers,
}

client, _ := tus.NewClient("https://api.cloudflare.com/client/v4/accounts/"+ accountID +"/media", config)

upload, _ := tus.NewUploadFromFile(sourceFile)

uploader, _ := client.CreateUpload(upload)

uploader.Upload()
  • 写回答

1条回答 默认 最新

  • duan117890 2019-07-08 15:08
    关注

    This is actually related to the go-tus client.

    Cloudflare's example creates a tus.Upload from an *os.File, but rather than trying to "convert" your multipart.File to an *os.File, I would consider the other functions go-tus provides for getting a tus.Upload.

    Looking at the docs, you should consider these two:

    • func NewUpload(reader io.Reader, size int64, metadata Metadata, fingerprint string) *Upload
    • func NewUploadFromBytes(b []byte) *Upload

    Considering multipart.File implements the io.Reader interface, you can go with both of these. Which is best depends on your use case, but if the files being uploaded have a size of more than several tens of KB's, you should really NewUpload. NewUploadFromBytes forces you to read the entire file into memory first.

    In case you need some inspiration for what the size, metadata and fingerprint arguments should contain, look at the implementation of NewUploadFromFile.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格