fix download google file not found or in private mode

This commit is contained in:
namhq1989 2022-12-01 09:14:15 +07:00
parent ee6b77b4fa
commit 1917722b3a
2 changed files with 40 additions and 10 deletions

View File

@ -7,6 +7,7 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"strings"
"github.com/tanaikech/go-getfilelist" "github.com/tanaikech/go-getfilelist"
"google.golang.org/api/drive/v3" "google.golang.org/api/drive/v3"
@ -84,19 +85,14 @@ func (g GoogleDrive) GetFilesByFolderID(folderID string, mimeType []string) ([]G
return result, nil return result, nil
} }
func (g GoogleDrive) DownloadByFileID(id, name, location string) (err error) { // DownloadByFileID download file into specific path
fmt.Printf("[google drive] start download file %s \n", name) func (g GoogleDrive) DownloadByFileID(id, path string) (err error) {
defer fmt.Printf("[google drive] done download file %s \n", name) // trim "/" in the end of path
path = strings.TrimSuffix(path, "/")
// prepare url
url := fmt.Sprintf("https://drive.google.com/uc?export=download&id=%s", id) url := fmt.Sprintf("https://drive.google.com/uc?export=download&id=%s", id)
// Create the file
out, err := os.Create(location)
if err != nil {
return err
}
defer out.Close()
// Get the data // Get the data
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
@ -109,6 +105,27 @@ func (g GoogleDrive) DownloadByFileID(id, name, location string) (err error) {
return fmt.Errorf("bad status: %s", resp.Status) return fmt.Errorf("bad status: %s", resp.Status)
} }
// get file name
filename := getFileNameFromHeaderContentDisposition(resp.Header.Get("Content-Disposition"))
// return err if not found
if filename == "" {
return errors.New("file is not existed or is in private mode, please check again")
}
// assign location with field name
location := fmt.Sprintf("%s/%s", path, filename)
// Create the file
out, err := os.Create(location)
if err != nil {
return err
}
defer out.Close()
fmt.Printf("[google drive] start download file %s with id %s \n", filename, id)
defer fmt.Printf("[google drive] done download file %s with id %s \n", filename, id)
// Writer the body to file // Writer the body to file
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
if err != nil { if err != nil {

13
util.go Normal file
View File

@ -0,0 +1,13 @@
package download
import (
"mime"
)
func getFileNameFromHeaderContentDisposition(value string) string {
disposition, params, err := mime.ParseMediaType(value)
if err != nil || disposition != "attachment" {
return ""
}
return params["filename"]
}