duanmeng9336 2017-12-26 07:41
浏览 90
已采纳

在http中输出一个.mp4文件,将问题从数据库拖到浏览器

answered

I am having a hard time with Mongodb and Gridfs, using it with Go's http package. I am trying to store a .mp4 file into Gridfs, then pull it out into the browser for playback.

Heres what I am doing now. It successfully pulls the file from database, I could even write it correctly to a download location.

// Connect to database
// Session to database

func movie(w http.ResponseWriter r *http.Request) {
    file, err := db.GridFS("fs").Open("movie.mp4")
    if err != nil {
        log.Println(err)
    }
    defer file.Close()

    w.Header.Set("Content-type", "video/mp4")
    if _, err := io.Copy(w, file); err != nil {
    log.Println(err)
    } 
    // I am trying to send it to the browser.
    // I want to achieve same thing as, http://localhost/view/movie.mp4, 
    as if you did that.
}

If the file was on the server, I would just do something like this. But instead I am trying to store it in Mongodb, for all around easier use involving metadata.

func movie(w http.ResponseWriter r *http.Request) {
    http.ServeFile("./uploads/movie.mp4") // Easy
}

The browser is receiving something, but its just malformed or corrupted. Just shows the video player with an error message. Any help would be appreciated, I have only been programming a week.

Here is a picture of the error, no console error messages.

enter image description here

Unless someone has an alternative to storing video files for playback in browser somewhere other than MongoDB or Amazon S3. Please let me know, thanks.

  • 写回答

1条回答 默认 最新

  • dongxu0690 2017-12-27 08:52
    关注

    You may want to check http.ServeContent. It will handle all the mess (content-type, content-length, partial data, cache) automaticlly and save you a lot of time. It takes a ReadSeeker to serve, which GridFile already implented. So your code may simply change to the below.

    func movie(w http.ResponseWriter r *http.Request) {
        file, err := db.GridFS("fs").Open("movie.mp4")
        if err != nil {
            log.Println(err)
        }
        defer file.Close()
    
        http.ServeContent(w,r,"movie.mp4",file.UploadDate(),file)
    
    }
    

    If that doesn't work, please use tools like curl or wget to download the served content and compare it to the orignal one (in db).

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

报告相同问题?

悬赏问题

  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)