POSTGRESQL:Golang working with BLOB

package main

import (

"fmt"

"io"

"io/ioutil"

"net/http"

"github.com/jinzhu/gorm"

_ "github.com/lib/pq"

)

type StudentDocuments struct {

ID int `gorm:"primary_key,AUTO_INCREMENT"`

ApplicationID int

FileName string

FileData byte

}

func main() {

db, err := gorm.Open("postgres", "port=5432 user=postgres dbname=studentdocumentsdb password=postgres")

if err != nil {

fmt.Println(err.Error())

panic("failed to connect Database")

}

defer db.Close()

if (!db.HasTable("StudentDocuments") && !db.HasTable(&StudentDocuments{})) {

db.CreateTable(&StudentDocuments{})

}

http.HandleFunc("/", uploadfile)

http.ListenAndServe(":8080", nil)

}

func uploadfile(w http.ResponseWriter, req *http.Request) {

var s string

fmt.Println(req.Method)

if req.Method == http.MethodPost {

// open

f, h, err := req.FormFile("q")

if err != nil {

http.Error(w, err.Error(), http.StatusInternalServerError)

return

}

defer f.Close()

// for your information

fmt.Println("\nfile:", f, "\nheader:", h, "\nerr", err)

// read

bs, err := ioutil.ReadAll(f)

if err != nil {

http.Error(w, err.Error(), http.StatusInternalServerError)

return

}

s = string(bs)

}

w.Header().Set("Content-Type", "text/html; charset=utf-8")

io.WriteString(w, `<form method="POST" enctype="multipart/form-data">
<input type="file" name="q">
<input type="submit">
</form><br>`+s)

}

//File stored in Fileserver

How to create Blob with Golang

Hi. FormFile returns a multpart.File which implements the Reader interface. Create an byte slice with the same size as the file and read the file into that slice and then you should be able to use that slice in a call to sql.Exec as an argument.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.