Table of Contents
Question content
Workaround
Home Backend Development Golang File upload to Google Drive via API fails

File upload to Google Drive via API fails

Feb 09, 2024 pm 01:30 PM
Internet problem

通过 API 将文件上传到 Google Drive 失败

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 ""
Copy after login

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
    }

        // ...

}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check the default gateway on your mobile phone (Easily understand and set the default gateway of your mobile phone) How to check the default gateway on your mobile phone (Easily understand and set the default gateway of your mobile phone) May 06, 2024 pm 06:28 PM

In order to perform network settings and troubleshooting, when using mobile phones to access the Internet, we often need to know the default gateway of the mobile phone. And to help readers understand relevant knowledge and operations, this article will introduce how to check the default gateway on the mobile phone. 1. What is the default gateway? It is responsible for sending data packets from the local network to the target network or device. The default gateway is the channel that connects the local network to the external network. 2. The importance of the default gateway. It determines how data packets enter and leave the mobile phone. The role of the default gateway on the mobile phone is similar to the doorway of a home. 3. Open the phone settings, find "Settings" on the home screen of the phone and click to enter the settings page and application icon. 4. Enter the network settings sliding screen and find it. Click "Network and Internet" on the settings page to enter the option. 5.

Reasons why Baidu Netdisk download failed 125201 Reasons why Baidu Netdisk download failed 125201 Apr 30, 2024 pm 10:42 PM

Baidu Netdisk download failed 125201 Error reason: Network problems: unstable/slow connection, router failure, busy server File problems: damaged/incomplete files, invalid links Baidu Netdisk restrictions: download limit exceeded, membership expiration/account restricted Browser/application issues: out-of-date version/poor compatibility, download manager failure System issues: viruses/malware, missing components/drivers

Why can't I see the links posted by others on Kuaishou? Why can't I see the links posted by others on Kuaishou? May 01, 2024 am 12:39 AM

The reasons why you cannot see the link on Kuaishou may include: content violations, geographical restrictions, network problems, browser settings, expired links, insufficient permissions or technical failures. Solutions include: check the network, disable ad blockers, change access devices, contact the publisher, contact the administrator or wait for the platform to be fixed.

The data resource of King of Glory is damaged. You need to restart the client to repair the resource. Solution The data resource of King of Glory is damaged. You need to restart the client to repair the resource. Solution May 05, 2024 pm 03:40 PM

After the King of Glory update, some players were ejected after entering the game. I don’t know what happened and how to solve it. The editor below will show that the King of Glory data resources are damaged and you need to restart the client to repair the resources. Solution. The data resources of Honor of Kings are damaged. You need to restart the client to repair the resources. How to solve this problem? There may be several reasons for this situation. The first is that the version is not updated completely, the second is a game bug, and the third may be a network problem. . 1. Reason 1: Version update problem. Players need to update the new version completely. If each update is complete, uninstall the game first and then update the full version again. 2. Reason 2: Game bugs. Bugs that appear after the game is updated. In this case, they can only be repaired through the official website.

What to do if there is a network error on Eureka Exchange What to do if there is a network error on Eureka Exchange Jul 17, 2024 pm 04:25 PM

When encountering an EEX exchange network error, you can take the following steps to resolve it: Check your Internet connection. Clear browser cache. Try another browser. Disable browser plug-ins. Contact Ouyi customer service.

How to solve the problem of slow download of mobile Baidu network disk How to solve the problem of slow download of mobile Baidu network disk Apr 30, 2024 pm 09:27 PM

Reasons for the slow download speed of mobile Baidu Netdisk include: network instability, server congestion, download restrictions, software interception, insufficient storage, low version, and poor device compatibility.

Why can't I log in to okx? Why can't I log in to okx? Jul 10, 2024 pm 05:33 PM

The reasons why OKX cannot log in and its solutions include: check whether the network connection is stable and try to switch to a different network. Make sure the username and password are correct. The account may be locked due to multiple incorrect password entries. Please wait for a period of time before trying to log in again. Clear your browser cache and cookies and try logging in using a different browser. The website may be under maintenance, please wait for the maintenance to be completed and try again. Accounts may be frozen or disabled due to violation of terms, please contact customer service for information. Make sure the device meets OKX supported operating system and device requirements.

Why can't I register at the Bitget Wallet exchange? Why can't I register at the Bitget Wallet exchange? Sep 06, 2024 pm 03:34 PM

There are various reasons for being unable to register for the BitgetWallet exchange, including account restrictions, unsupported regions, network issues, system maintenance and technical failures. To register for the BitgetWallet exchange, please visit the official website, fill in the information, agree to the terms, complete registration and verify your identity.

See all articles