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 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加