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

如何在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.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?