golang保存图片到数据库

图片保存到数据库通常有两种做法:一是把图片转化成二进制形式,然后保存到数据库中;二是将图片保存的路径存储在数据库中。
由于图片一般都在几M,所以当以二进制流的形式保存到数据库中时,在高并发的情况下,会加重数据库的负担。(至于更详细的原因,后期文章会做分享)因此大多数会选择第二种做法。下面就是以第二种方式进行图片保存的。

uploadImg.go

package main

import (
    "net/http"
    "html/template"
    "fmt"
    "strings"
    "os"
    "io"
    "gopkg.in/mgo.v2/bson"
    "gopkg.in/mgo.v2"
)

const UPLOAD_PATH string = "C:/Users/benben/Desktop/"

type Img struct {
    Id     bson.ObjectId `bson:"_id"`
    ImgUrl string        `bson:"imgUrl"`
}

func main() {
    http.HandleFunc("/entrance", Entrance)
    http.HandleFunc("/uploadImg", UploadImg)
    http.ListenAndServe(":8000", nil)
}

func Entrance(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("uploadImg.html")
    t.Execute(w, nil)
}

func UploadImg(w http.ResponseWriter, r *http.Request) {
    var img Img
    img.Id = bson.NewObjectId()

    r.ParseMultipartForm(1024)
    imgFile, imgHead, imgErr := r.FormFile("img")
    if imgErr != nil {
        fmt.Println(imgErr)
        return
    }
    defer imgFile.Close()

    imgFormat := strings.Split(imgHead.Filename, ".")
    img.ImgUrl = img.Id.Hex() + "." + imgFormat[len(imgFormat)-1]

    image, err := os.Create(UPLOAD_PATH + img.ImgUrl)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer image.Close()

    _, err = io.Copy(image, imgFile)
    if err != nil {
        fmt.Println(err)
        return
    }

    session, err := mgo.Dial("")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    err = session.DB("images").C("image").Insert(img)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("success to upload img")
}

uploadImg.html文件


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Documenttitle>
head>
<body>
<form action="/uploadImg" method="post" enctype="multipart/form-data">
    图片:<br>
    <input type="file" name="img" value="请上传图片">
    <br><br>
    <input type="submit" value="submit">
form>
body>
html>

uploadImg.go文件和uploadImg.html处于同一目录下,成功执行后,数据库会插入一条图片记录,本地服务器中的UPLOAD_PATH目录下存有上传的图片。

你可能感兴趣的:(GO学习总结)