Upload Image from url (#1193)

This commit is contained in:
WithoutPants
2021-03-11 12:56:34 +11:00
committed by GitHub
parent b3966b3c76
commit 55aee21cff
13 changed files with 205 additions and 26 deletions

View File

@@ -4,11 +4,66 @@ import (
"crypto/md5"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
)
// Timeout to get the image. Includes transfer time. May want to make this
// configurable at some point.
const imageGetTimeout = time.Second * 60
const base64RE = `^data:.+\/(.+);base64,(.*)$`
// ProcessImageInput transforms an image string either from a base64 encoded
// string, or from a URL, and returns the image as a byte slice
func ProcessImageInput(imageInput string) ([]byte, error) {
regex := regexp.MustCompile(base64RE)
if regex.MatchString(imageInput) {
_, d, err := ProcessBase64Image(imageInput)
return d, err
}
// assume input is a URL. Read it.
return ReadImageFromURL(imageInput)
}
// ReadImageFromURL returns image data from a URL
func ReadImageFromURL(url string) ([]byte, error) {
client := &http.Client{
Timeout: imageGetTimeout,
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// assume is a URL for now
// set the host of the URL as the referer
if req.URL.Scheme != "" {
req.Header.Set("Referer", req.URL.Scheme+"://"+req.Host+"/")
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
// ProcessBase64Image transforms a base64 encoded string from a form post and returns the MD5 hash of the data and the
// image itself as a byte slice.
func ProcessBase64Image(imageString string) (string, []byte, error) {
@@ -16,7 +71,7 @@ func ProcessBase64Image(imageString string) (string, []byte, error) {
return "", nil, fmt.Errorf("empty image string")
}
regex := regexp.MustCompile(`^data:.+\/(.+);base64,(.*)$`)
regex := regexp.MustCompile(base64RE)
matches := regex.FindStringSubmatch(imageString)
var encodedString string
if len(matches) > 2 {