php editor Xigua tells you that sometimes we may encounter failures when using the API to upload files to Google Drive. This situation may be caused by various reasons, such as network problems, insufficient permissions, etc. But don’t worry, there are some things we can do to fix this problem. Next, we will introduce in detail how to successfully upload files to Google Drive through the API, so that everyone will no longer worry about this problem.
Question content
I'm trying to upload a file to my Google Drive but it's failing. I thought I had specified the MIME type correctly because I found this to be a common problem, but it still doesn't work for me.
About the conversion system: I have an API for Gin-Gonic (v1.9.1) where I can upload files. The file is successfully passed from the frontend/postman to the API as I can successfully save the file I got from the API.
The error I get is:
Post "https://www.googleapis.com/upload/drive/v3/files?alt=json&prettyPrint=false&uploadType=multipart": Post "": unsupported protocol scheme ""
I have the following function:
func (c *Client) UploadFile(oauthTokenConfig GoogleOauthTokenConfig, parentFolderId string, fileHeader *multipart.FileHeader) (*string, error) { svc, err := drive.NewService(context.Background(), option.WithHTTPClient( oauthTokenConfig.Config.Client( context.Background(), &oauth2.Token{ AccessToken: oauthTokenConfig.AccessToken, TokenType: oauthTokenConfig.TokenType, RefreshToken: oauthTokenConfig.RefreshToken, Expiry: oauthTokenConfig.ExpiresIn, }, )), ) if err != nil { return nil, err } fileExtension := filepath.Ext(fileHeader.Filename) fileName := strings.TrimSuffix(fileHeader.Filename, fileExtension) fileMimeType := fileHeader.Header.Get("Content-Type") uploadFileMetaData := drive.File{ Name: fmt.Sprintf("%s%s", fileName, fileExtension), // fmt.Sprintf("%s_%s%s", fileName, uuid.New().String(), fileExtension), Parents: []string{parentFolderId}, MimeType: fileMimeType, } file, err := fileHeader.Open() if err != nil { return nil, err } defer file.Close() fileResult, err := svc.Files. Create(&uploadFileMetaData). Media(file, googleapi.ContentType("text/plain")). Do() if err != nil { return nil, err // here I get the error } // ... }
I added a hardcoded MIME type here, but the variable fileMimeType
is actually correct. I uploaded a Test.txt file containing the contents of Test1 (which was also created successfully when I sent it via Frontend/Postman). I've also tried specifying the file MIME type dynamically or not specifying the MIME type at all, but always get the same result.
I use the following packages for this:
- Go version:
go1.21.1 darwin/arm64
- go list -m golang.org/x/oauth2: v0.13.0
- go list -m google.golang.org/api: v0.147.0
- google.golang.org/api/drive/v3
- google.golang.org/api/googleapi
- google.golang.org/api/option
edit:
I also copied Google’s official example, but it still doesn’t work.
Workaround
Looks like the error is related to authentication. It's a bit difficult to deduce the invalid authentication from this error, but I had to change the refresh token's refresh algorithm a bit to get it to work.
This is my working code. Note that before calling the UploadFile()
function, I first check oauthTokenConfig.ExpiresIn
to see if the token is still valid, if so, upload the file, otherwise I first refresh the token .
File Upload
func (c *Client) UploadFile(oauthTokenConfig GoogleOauthTokenConfig, parentFolderId string, file *multipart.FileHeader) (*string, error) { svc, err := drive.NewService(context.Background(), option.WithHTTPClient( oauthTokenConfig.Config.Client( context.Background(), &oauth2.Token{ AccessToken: oauthTokenConfig.AccessToken, TokenType: oauthTokenConfig.TokenType, RefreshToken: oauthTokenConfig.RefreshToken, Expiry: oauthTokenConfig.ExpiresIn, }, )), ) if err != nil { return nil, fmt.Errorf("failed to create drive-service: %s", err.Error()) } fileExtension := filepath.Ext(file.Filename) fileName := strings.TrimSuffix(file.Filename, fileExtension) uploadFile := drive.File{ Name: fmt.Sprintf("%s_%s%s", fileName, uuid.New().String(), fileExtension), Parents: []string{parentFolderId}, } fileContent, err := file.Open() if err != nil { return nil, fmt.Errorf("failed to open file: %s", err.Error()) } fileResult, err := svc.Files.Create(&uploadFile).Media(fileContent).Do() if err != nil { return nil, fmt.Errorf("failed to create file: %s", err.Error()) } uploadedFile, err := svc.Files.Get(fileResult.Id).Fields("webViewLink").Do() if err != nil { return nil, fmt.Errorf("failed to get file: %s", err.Error()) } return &uploadedFile.WebViewLink, nil }
Refresh Token
func (c *Client) RefreshToken(oauthTokenConfig GoogleOauthTokenConfig) (*GoogleOauthTokenConfig, error) { ctx := context.Background() config := oauth2.Config{ ClientID: c.ClientId, ClientSecret: c.ClientSecret, RedirectURL: oauthTokenConfig.Config.RedirectURL, Scopes: []string{"https://www.googleapis.com/auth/drive"}, Endpoint: google.Endpoint, } token := &oauth2.Token{ AccessToken: oauthTokenConfig.AccessToken, TokenType: oauthTokenConfig.TokenType, RefreshToken: oauthTokenConfig.RefreshToken, Expiry: oauthTokenConfig.ExpiresIn, } tokenSource := config.TokenSource(ctx, token) updatedToken, err := tokenSource.Token() if err != nil { return nil, err } return &GoogleOauthTokenConfig{ Config: config, AccessToken: updatedToken.AccessToken, RefreshToken: updatedToken.RefreshToken, ExpiresIn: updatedToken.Expiry, TokenType: updatedToken.TokenType, }, nil }
The above is the detailed content of File upload to Google Drive via API fails. For more information, please follow other related articles on the PHP Chinese website!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
