duanshaiduhao2471 2019-07-08 14:14
浏览 1748

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

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



  • ¥15 abaqus里的python算法
  • ¥15 单细胞测序筛选簇中基因
  • ¥100 如何在思科模拟器中进入CEF模式
  • ¥15 Simulink 仿真如何使用MATLAB function模块获取到仿真过程中某一仿真时刻输入到模块的函数的值?
  • ¥50 关于#微信小程序#的问题:微信小程序支持h5实现webrtc h264 h265低延迟传输渲染,能付费帮我们解决一下吗
  • ¥20 请问ansys License manager 这个问题如何解决
  • ¥15 memory.limit()' is no longer supported
  • ¥15 基于stm32f4产生两路pwm信号并可由串口通信调节
  • ¥15 C++/QT设置函数调用条件(多个功能调用同一,且各自调用条件不同)
  • ¥15 UE5样条线生成的网格UV问题