O upload por formulário permite que você envie objetos diretamente para o Object Storage Service (OSS) usando formulários HTML padrão de aplicativos web. Este tópico descreve como gerar informações como uma assinatura e uma política de upload usando o OSS SDK para Go 2.0 e usar o método HTTP Post para enviar um objeto para o OSS.
Observações de uso
-
O código de exemplo neste tópico usa o ID da região
cn-hangzhouda região China (Hangzhou). Por padrão, o endpoint público é usado para acessar recursos em um bucket. Se você quiser acessar recursos no bucket usando outros serviços do Alibaba Cloud na mesma região em que o bucket está localizado, use o endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints. -
Neste tópico, as credenciais de acesso são obtidas das variáveis de ambiente. Para obter mais informações sobre como configurar as credenciais de acesso, consulte Configurar credenciais de acesso.
-
O tamanho do objeto que você deseja enviar usando o upload por formulário não pode exceder 5 GB.
Exemplos
O código de exemplo a seguir fornece um exemplo de como realizar o upload por formulário. O processo completo de upload por formulário consiste nas seguintes etapas:
-
Criar uma política de upload: Especifique o período de validade e as condições de uma solicitação de upload, incluindo o nome do bucket, versão da assinatura, credenciais, data da solicitação e intervalo de comprimento do corpo da solicitação.
-
Processar a política de upload: Converta a política de upload em uma string JSON e codifique a string em Base64.
-
Gerar uma chave de assinatura: Use o algoritmo HMAC-SHA256 para gerar uma chave de assinatura incluindo a data, região, serviço e tipo de solicitação.
-
Calcular uma assinatura: Use a chave de assinatura gerada para assinar a string da política codificada em Base64 e converta a assinatura em uma string hexadecimal.
-
Construir um corpo de solicitação: Crie um gravador de formulário multipart, especifique a chave do objeto, política, versão da assinatura, credenciais, data da solicitação e assinatura no formulário, e escreva os dados que você deseja enviar no formulário.
-
Criar e executar uma solicitação: Crie uma solicitação HTTP POST e especifique os cabeçalhos da solicitação. Envie a solicitação e verifique o código de status da resposta para garantir que a solicitação foi bem-sucedida.
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"hash"
"io"
"log"
"mime/multipart"
"net/http"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
product = "oss"
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Create a credential provider.
credentialsProvider := credentials.NewEnvironmentVariableCredentialsProvider()
cred, err := credentialsProvider.GetCredentials(context.TODO())
if err != nil {
log.Fatalf("GetCredentials fail, err:%v", err)
}
// Specify the content that you want to upload.
content := "hi oss"
// Create an upload policy.
utcTime := time.Now().UTC()
date := utcTime.Format("20060102")
expiration := utcTime.Add(1 * time.Hour)
policyMap := map[string]any{
"expiration": expiration.Format("2006-01-02T15:04:05.000Z"),
"conditions": []any{
map[string]string{"bucket": bucketName},
map[string]string{"x-oss-signature-version": "OSS4-HMAC-SHA256"},
map[string]string{"x-oss-credential": fmt.Sprintf("%v/%v/%v/%v/aliyun_v4_request",
cred.AccessKeyID, date, region, product)}, // Specify the credentials.
map[string]string{"x-oss-date": utcTime.Format("20060102T150405Z")},
// Specify other conditions.
[]any{"content-length-range", 1, 1024},
// []any{"eq", "$success_action_status", "201"},
// []any{"starts-with", "$key", "user/eric/"},
// []any{"in", "$content-type", []string{"image/jpg", "image/png"}},
// []any{"not-in", "$cache-control", []string{"no-cache"}},
},
}
// Convert the upload policy to a JSON string.
policy, err := json.Marshal(policyMap)
if err != nil {
log.Fatalf("json.Marshal fail, err:%v", err)
}
// Base64-encode the JSON string.
stringToSign := base64.StdEncoding.EncodeToString([]byte(policy))
// Generate a signing key.
hmacHash := func() hash.Hash { return sha256.New() }
signingKey := "aliyun_v4" + cred.AccessKeySecret
h1 := hmac.New(hmacHash, []byte(signingKey))
io.WriteString(h1, date)
h1Key := h1.Sum(nil)
h2 := hmac.New(hmacHash, h1Key)
io.WriteString(h2, region)
h2Key := h2.Sum(nil)
h3 := hmac.New(hmacHash, h2Key)
io.WriteString(h3, product)
h3Key := h3.Sum(nil)
h4 := hmac.New(hmacHash, h3Key)
io.WriteString(h4, "aliyun_v4_request")
h4Key := h4.Sum(nil)
// Calculate the signature.
h := hmac.New(hmacHash, h4Key)
io.WriteString(h, stringToSign)
signature := hex.EncodeToString(h.Sum(nil))
// Build a Post request body.
bodyBuf := &bytes.Buffer{}
// Create a multipart form writer to build the request body.
bodyWriter := multipart.NewWriter(bodyBuf)
// Specify the object information, including the key and metadata.
bodyWriter.WriteField("key", objectName) // Specify the object key (object name).
// bodyWriter.WriteField("x-oss-", value) // Specify the metadata. This parameter is optional.
// Specify the Base64-encoded policy string.
bodyWriter.WriteField("policy", stringToSign)
// Specify the signature version.
bodyWriter.WriteField("x-oss-signature-version", "OSS4-HMAC-SHA256")
// Specify the credentials.
bodyWriter.WriteField("x-oss-credential", fmt.Sprintf("%v/%v/%v/%v/aliyun_v4_request", cred.AccessKeyID, date, region, product))
// Specify the request date.
bodyWriter.WriteField("x-oss-date", utcTime.Format("20060102T150405Z"))
// Specify the signature.
bodyWriter.WriteField("x-oss-signature", signature)
// Create a form field named "file" to upload data.
w, _ := bodyWriter.CreateFormField("file")
// Write the data that you want to upload to the form field.
w.Write([]byte(content))
// Close the form writer and make sure that all data is written to the request body as expected.
bodyWriter.Close()
// Create a Post request.
req, _ := http.NewRequest("POST", fmt.Sprintf("http://%v.oss-%v.aliyuncs.com/", bucketName, region), bodyBuf)
req.Header.Set("Content-Type", bodyWriter.FormDataContentType())
// Execute the Post request.
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Do fail, err:%v", err)
}
defer resp.Body.Close()
// Check the response status code.
if resp.StatusCode/100 != 2 {
log.Fatalf("Post Object Fail, status code:%v, reason:%v", resp.StatusCode, resp.Status)
}
log.Printf("post object done, status code:%v, request id:%v\n", resp.StatusCode, resp.Header.Get("X-Oss-Request-Id"))
}
Referências
-
Para o código de exemplo completo usado para realizar o upload por formulário, visite GitHub.