试图上传图像通过一个api和存储在一个mysql数据库

slsn1g29  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(330)

所以我尝试通过一个api上传图像并将其存储在mysql数据库中。我不知道如何转换 imageFile 我可以储存在数据库里。
我正试着把这张照片储存到 blob 场上的 image 此表的列:

CREATE TABLE runkdb.uploaded_challenge (
    id int NOT NULL AUTO_INCREMENT,
    challenge_id int NOT NULL,
    user_id int NOT NULL,
    created_at DATETIME NOT NULL,
    image_caption TEXT,
    image_path varchar(255),
    image BLOB,
    score int DEFAULT 0,
    primary key (id)
);

这是尝试存储数据的api函数的一部分:

// Parse the request
imageFile := make([]byte, 0)
image, _, err := req.FormFile("image")
if err != nil {
    // No image
    glog.Error("Error parsing image")
    responseMessage.Message = "Error parsing image"
    w.WriteHeader(400)
    json.NewEncoder(w).Encode(responseMessage)
    return
} else {
    //if !strings.HasPrefix(fileHeader.Header["Content-Type"][0], "image") {
        // Something wrong with file type
    //}
    imageFile, err = ioutil.ReadAll(image)
    if err != nil {
        // Error reading uploaded image from stream
        glog.Error("Error reading image")
        responseMessage.Message = "Error reading image"
        w.WriteHeader(400)
        json.NewEncoder(w).Encode(responseMessage)
        return
    }
}

imageCaption := req.Form.Get("image_caption")

// Create DB connection
txn, err := api.db.Begin()
if err != nil {
    glog.Error("Error creating database transaction")
    responseMessage.Message = "Error creating database transaction"
    w.WriteHeader(500)
    json.NewEncoder(w).Encode(responseMessage)
    return
}

t := time.Now()
createdAtTimeString := fmt.Sprintf(t.Format("2006-01-02 15:04:05"))
imageByteString := string(imageFile)
query := fmt.Sprintf("INSERT INTO uploaded_challenge (challenge_id, user_id, created_at, image_caption, image) VALUES ('%d', '%d', '%s', '%s', '%s');", id, userID, createdAtTimeString, imageCaption, imageByteString)
print(query)
result, err := txn.Exec(query)
if err != nil {
    txn.Rollback()
    glog.Error("Error inserting challenge into database")
    responseMessage.Message = "Error inserting challenge into database"
    w.WriteHeader(406)
    json.NewEncoder(w).Encode(responseMessage)
    return
}
8nuwlpux

8nuwlpux1#

通过转换我的 imageFile 对于这样的字符串: encodedImage := base64.StdEncoding.EncodeToString(imageFile) 然后我储存了 encodedImage 进入我的数据库 image 列(类型) BLOB )

相关问题