gpt4 book ai didi

go - 如何以程序方式上传图片?

转载 作者:行者123 更新时间:2023-12-03 10:08:37 25 4
gpt4 key购买 nike

如何自动将图像公开上传到Google Cloud Storage中?
我试过了
代码:

func HandleFileUploadToBucket(c *gin.Context) {
bucket := "mybucket"

var err error

ctx := appengine.NewContext(c.Request)

storageClient, err = storage.NewClient(ctx, option.WithCredentialsFile("keys.json"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"error": true,
})
return
}

f, uploadedFile, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"error": true,
})
return
}

defer f.Close()

sw := storageClient.Bucket(bucket).Object(uploadedFile.Filename).NewWriter(ctx)

sw.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}} // As you can see here I made it AllUser
sw.CacheControl = "public, max-age=86400"

if _, err := io.Copy(sw, f); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"error": true,
})
return
}

if err := sw.Close(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"error": true,
})
return
}

u, err := url.Parse("/" + bucket + "/user/" + sw.Attrs().Name)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"Error": true,
})
return
}

c.JSON(http.StatusOK, gin.H{
"message": "file uploaded successfully",
"pathname": u.EscapedPath(),
})
}
发生了什么事
我想要第一行
我得到第二排
结果:
pic

最佳答案

在我的代码中,分开upload filesetting the access privileges操作对我有用的是什么。它看起来像这样:

sw := storageClient.Bucket(bucket).Object(uploadedFile.Filename).NewWriter(ctx)

sw.CacheControl = "public, max-age=86400"

if _, err := io.Copy(sw, f); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"error": true,
})
return
}

if err := sw.Close(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
"error": true,
})
return
}

//set public access
acl := storageClient.Bucket(bucket).Object(uploadedFile.Filename).ACL()
if err := acl.Set(ctx, storage.AllUsers, storage.RoleReader); err != nil {
//handle error
}

关于go - 如何以程序方式上传图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64987419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com