Trying to upload image through an API and store it in a MySQL database

时间:2018-10-09 06:52:36

标签: mysql go multipartform-data

So I'm trying to upload image through an API and store it in a MySQL database. I'm unsure how to convert the imageFile to something that I can store in my DB.

I'm trying to store this image into a blob field on the image column of this table:

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)
);

This is part of the API function that tries to store the data:

// 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
}

1 个答案:

答案 0 :(得分:1)

通过将我的imageFile转换为这样的字符串来解决它:

encodedImage := base64.StdEncoding.EncodeToString(imageFile)

然后我将encodedImage存储到数据库的image列(类型为BLOB