将 .xlsx 文件上传到谷歌云存储

时间:2021-04-06 08:32:12

标签: go google-cloud-storage 360entsecgroup-skylar-excelize

我用 Go 编写了这个 API,它使用 excelize 从我想上传到私有 GCS 存储桶的数据库中获取的数据创建一个 .xlsx 文件。但问题是在我上传文件后,它说文件类型是 application/zip 而不是 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

type Connection struct {
    Credential    string
    BucketName    string
    APIKey        string
    ProjectID     string
    AccessToken   string
    BaseURL       string
    GcpCredential *google.Credentials
}

func (conn *Connection) Upload(url, name string) (err error) {
    ctx := context.Background()
    client, err := storage.NewClient(ctx, option.WithCredentialsFile(conn.Credential))
    if err != nil {
        return err
    }

    err = write(client, conn.BucketName, name, url)

    return err
}

func write(client *storage.Client, bucket, object, url string) error {
    ctx := context.Background()
    f, err := os.Open(url)
    if err != nil {
        return err
    }
    defer f.Close()

    wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
    _, err = io.Copy(wc, f)
    if err != nil {
        return err
    }
    if err := wc.Close(); err != nil {
        return err
    }

    return nil
}

//In other file, generate excel file and upload it using above code
xlsx := excelize.NewFile()
//setup file content
...

//save to local machine located in uploadURL
err = xlsx.SaveAs(uploadURL)

//then upload to GCS bucket
err = h.Googlestorage.Upload(uploadURL, fileNameInGCS)
if err != nil {
    SendBadRequest(w, err.Error())
    return
}

//then generate signed URL for client to access the file

这是一个问题,因为当我生成文件的签名 URL 时,它下载为 .zip 文件而不是 .xlsx。

"{file path in bucket}.xlsx?Expires=1617698911&
GoogleAccessId={googleAccessID}&
Signature={someGeneratedSignature}"

我该如何解决这个问题?我上传文件的方式有问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用 ObjectHandle.Update function


    _, err := client.Bucket(bucket).Object(object).Update(ctx, storage.ObjectAttrsToUpdate{
        ContentType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    })