func (s *S) TestGridFSOpenNext(c *C) { session, err := mgo.Dial("localhost:40011") c.Assert(err, IsNil) defer session.Close() db := session.DB("mydb") gfs := db.GridFS("fs") file, err := gfs.Create("myfile1.txt") c.Assert(err, IsNil) file.Write([]byte{'1'}) file.Close() file, err = gfs.Create("myfile2.txt") c.Assert(err, IsNil) file.Write([]byte{'2'}) file.Close() var f *mgo.GridFile var b [1]byte iter := gfs.Find(nil).Sort("-filename").Iter() ok := gfs.OpenNext(iter, &f) c.Assert(ok, Equals, true) c.Check(f.Name(), Equals, "myfile2.txt") _, err = f.Read(b[:]) c.Assert(err, IsNil) c.Assert(string(b[:]), Equals, "2") ok = gfs.OpenNext(iter, &f) c.Assert(ok, Equals, true) c.Check(f.Name(), Equals, "myfile1.txt") _, err = f.Read(b[:]) c.Assert(err, IsNil) c.Assert(string(b[:]), Equals, "1") ok = gfs.OpenNext(iter, &f) c.Assert(ok, Equals, false) c.Assert(iter.Close(), IsNil) c.Assert(f, IsNil) // Do it again with a more restrictive query to make sure // it's actually taken into account. iter = gfs.Find(bson.M{"filename": "myfile1.txt"}).Iter() ok = gfs.OpenNext(iter, &f) c.Assert(ok, Equals, true) c.Check(f.Name(), Equals, "myfile1.txt") ok = gfs.OpenNext(iter, &f) c.Assert(ok, Equals, false) c.Assert(iter.Close(), IsNil) c.Assert(f, IsNil) }
func GetFileData(name string) []byte { var ( result []byte file *mgo.GridFile err error ) file = GetGridFile(name) result = make([]byte, file.Size()) _, err = file.Read(result) check(err) return result }
// 查找文件 func FindAllFiles() { gfs := db.GridFS("fs") iter := gfs.Find(nil).Iter() var f *mgo.GridFile for gfs.OpenNext(iter, &f) { fmt.Printf("Filename: %s, %v\n", f.Name(), f.Id()) b := make([]byte, 512) w, err := os.Create("upload/" + f.Name()) if err != nil { continue } for { n, _ := f.Read(b) if n == 0 { break } w.Write(b[0:n]) } defer w.Close() } if iter.Err() != nil { panic(iter.Err()) } }