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)

  • 写回答

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 深度学习运行代码直接中断
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥20 需要完整的共散射点成像代码
  • ¥15 编写vba代码实现数据录入工作
  • ¥15 做过TCL海信电视小米电视相关影视会员软件私我
  • ¥15 Mapreduce是正常的,在运行其他jar包时并没有任何问题,只是在做LogCount.jar 时出的问题。如图所示
  • ¥15 ImportError: DLL load failed while importing _iterative: 找不到指定的模块。
  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢