lundi 6 avril 2020

Close File upload Connection if Content-type is not allowed in Golang

I've been trying to stop file uploading process if I check the first 3072 bytes and the content-type is not allowed. Right now it gives the response after it has been uploaded.

How can I stop the uploading process after just checking the first 3072 bytes?

My code :

// imported     "github.com/gabriel-vasile/mimetype"


const (
    MB = 1 << 20
)


func Uploader() {
r.ParseMultipartForm(10 * MB)
        r.Body = http.MaxBytesReader(w, r.Body, 30*MB)
        file, handler, err := r.FormFile("upload")
        if handler != nil {
            fmt.Println(handler.Header)
        }
        if err != nil {
            fmt.Println(err)
        }
        data := make([]byte, 3072)
        if _, err = file.Read(data); err != nil {
            panic(err)
        }
        if _, err = file.Seek(0, 0); err != nil {
            panic(err)
        }
        mime := mimetype.Detect(data)
        log.Printf("MIME: %#v\n", mime.String())
        allowedContentType := map[string]string{"video/mp4": "mp4", "audio/mpeg": "mp3"}
        if _, ok := allowedContentType[mime.String()]; ok == false {
            w.WriteHeader(http.StatusForbidden)
        } else {
       defer file.Close()

            f, err := os.OpenFile("../path/to/upload, os.O_WRONLY|os.O_CREATE, 0666)
            if err != nil {
                fmt.Println(err)
                panic(err)
            }

            defer f.Close()
            io.Copy(f, file)
}
...



Aucun commentaire:

Enregistrer un commentaire