dqj29136 2017-10-17 07:36
浏览 178

使用GoLang mgo将PDF保存在MongoDb中

I read multiple blogs about saving the file using mgo, but unable to find a solution for below specific need, help shoutout!

Below inserts object in MongoDb:

var dbSchoolPojo dbSchool
i := bson.NewObjectId()
dbSchoolPojo.ID = i
coll := db.C("school")

Below able to get hold of file:

file, handler, err := r.FormFile("pdf") //Able to get file from r *http.Request

Now, before inserting object, I need to set above file like:

dbSchoolPojo.pdf = file.Bytes(); //Of course Bytes() is invalid method

My structs object:

type dbSchool struct {
    ID  bson.ObjectId  `json:"id" bson:"_id,omitempty"`
    Pdf  []byte  `json:"pdf" bson:"pdf"`

In layman's term, the question is: How do I insert file (received from HTML form) in mongoDb via GoLang struct using mgo driver?

Thanks for reading! :)


PDF is stored in MongoDB like below:


Below code works without error, but doesn't serve PDF file:

func DownloadPdf(w http.ResponseWriter, r *http.Request, db mongoDB) {
    var school dbSchool
    coll := db.C("schools")

    incomingId = "59e6404e2f68182a74610f19"; //This mongo DB _id is received from GET URL request

    err := coll.Find(bson.M{"_id": bson.ObjectIdHex(incomingId)}).
        Select(bson.M{"pdf": 1}).One(&school)
    if err != nil {
        serve404(w, r, db)

    buffer := school.Pdf
    w.Header().Set("Content-Disposition", "attachment; filename=abc.pdf")
    w.Header().Set("Content-Type", "application/pdf")
    w.Header().Set("Content-Length", strconv.Itoa(len(buffer)))

    if _, err := w.Write(buffer); err != nil {
        log.Println("unable to serve image.") //This line is not executed

JQuery code to request content:

      $(".downloadPdfFile").click(function() {
            var domain = document.location.origin;
            window.open(domain+'/brochure/59e6404e2f68182a74610f19', '_blank');
  • 写回答



      相关推荐 更多相似问题


      • ¥15 用MATLAB解决问题,需要代码
      • ¥45 关于C语言设计井字棋游戏问题的实现
      • ¥20 vuforia的Unity3D开发,模型附上特效后大量报错
      • ¥35 Python实现文本关键词提取
      • ¥20 如何使用c++语言完成实验仪器管理系统
      • ¥15 请问Unity使用Magica Cloth插件怎么调整散兵的帘子和振袖比较好?
      • ¥15 请问为什么原神模型导入Unity做动画默认姿势会站不直?
      • ¥15 ld: cannot open C:\Program: No such file or directory
      • ¥15 请问汏佬要怎么访问这种过滤了post和get的php内容?
      • ¥15 C语言调用python脚本出现Debug Assertion Failed错误