回答
我在Mongodb和Gridfs上遇到困难,将它与Go的http包一起使用。我试图将.mp4文件存储到Gridfs中,然后将其拉出到浏览器中进行播放。
这是我现在正在做的事情。它成功地从数据库中提取文件,我甚至可以将其正确写入下载位置。
// 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.
}
如果文件在服务器上,我会做这样的事情。但相反,我试图将它存储在Mongodb中,因为更容易使用涉及元数据。
func movie(w http.ResponseWriter r *http.Request) {
http.ServeFile("./uploads/movie.mp4") // Easy
}
浏览器正在接收某些内容,但它只是格式错误或已损坏。只是向视频播放器显示错误消息。任何帮助将不胜感激,我只编程一周。
这是错误的图片,没有控制台错误消息。
除非有人可以替代存储视频文件,以便在MongoDB或Amazon S3以外的某个地方播放。请让我知道,谢谢。
你可能想检查http.ServeContent
。它将自动处理所有混乱(内容类型,内容长度,部分数据,缓存)并为您节省大量时间。它需要一个ReadSeeker来服务,GridFile已经实现了它。因此,您的代码可能只是更改为以下内容。
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)
}
如果这不起作用,请使用curl或wget等工具下载所提供的内容,并将其与orignal内容进行比较(在db中)。