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

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

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

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同