Skip to content

Instantly share code, notes, and snippets.

@isteshkov
Last active February 27, 2020 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isteshkov/3c6d7fc1c4f689bff2eaabaae49dacff to your computer and use it in GitHub Desktop.
Save isteshkov/3c6d7fc1c4f689bff2eaabaae49dacff to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"io"
"io/ioutil"
"github.com/h2non/filetype"
)
func uploadToTmpFile(reader *multipart.Reader) (string, string, *er.Error) {
var contentType string
f, err := ioutil.TempFile("", "")
if err != nil {
return "", contentType, er.VideoUploadError
}
defer f.Close()
for {
p, err := reader.NextPart()
if err != nil && err != io.EOF {
return "", contentType, er.VideoUploadError
}
if err == io.EOF {
break
}
buf := bufio.NewReader(p)
sniff, _ := buf.Peek(3072)
kind, _ := filetype.Match(sniff)
if kind.MIME.Type != MIMETypeVideo {
return "", contentType, er.WrongContentType
}
if kind == filetype.Unknown {
return "", contentType, er.UnknownFileType
}
if contentType == "" {
contentType = kind.MIME.Value
}
lmt := io.MultiReader(buf)
_, err = io.Copy(f, lmt)
if err != nil && err != io.EOF {
return "", contentType, er.VideoUploadError
}
}
if f.Name() == "" {
return "", contentType, er.VideoUploadError
}
return f.Name(), contentType, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment