为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过react/axios和golang/gin上传图片到S3

如何通过react/axios和golang/gin上传图片到S3

Go
一只名叫tom的猫 2023-07-04 16:55:09
我想通过以下步骤实现将图像发布到 S3 的功能。用户在屏幕上上传图像。提交后图像文件发送到服务器图像上传到服务器端(golang)的S3。现在问题是3。“图像已上传到服务器端(golang)的 S3。”服务器端代码没有错误。调试在此方法中显示 nil 值。form, _ := c.MultipartForm()
查看完整描述

1 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

我通过分离请求解决了这个问题。以下是我修复的代码。


//React

    const data = {

      title: this.state.title,

      content: this.state.content,

    };


    const res = await axios.post('http://localhost:2345/api/post', data);


    const formData = new FormData();

    for (var i in this.state.files) {

      formData.append('images[]', this.state.files[i]);

    }


    const resImageNames = await axios.post(

      'http://localhost:2345/api/post/image',

      formData,

      {

        headers: {'Content-Type': 'multipart/form-data'},

      }

    );

  }

//Golang

        api.POST("/post", func(c *gin.Context) {

            u, err := uuid.NewRandom()

            if err != nil {

                fmt.Println(err)

                return

            }

            uu := u.String()

            var article Article

            c.BindJSON(&article)

            ins, err := db.Prepare("INSERT INTO articles(uuid, title,content) VALUES(?,?,?)")

            if err != nil {

                log.Fatal(err)

            }

            ins.Exec(uu, article.TITLE, article.CONTENT)


            c.JSON(http.StatusOK, gin.H{"uuid": uu})


        })

        api.POST("/post/image", func(c *gin.Context) {

            creds := credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, token)


            cfg := aws.NewConfig().WithRegion("ap-northeast-1").WithCredentials(creds)

            svc := s3.New(session.New(), cfg)


            form, _ := c.MultipartForm()


            files := form.File["images[]"]


            var imageNames []ImageName

            imageName := ImageName{}


            for _, file := range files {


                f, err := file.Open()


                if err != nil {

                    log.Println(err)

                }


                defer f.Close()


                size := file.Size

                buffer := make([]byte, size)


                f.Read(buffer)

                fileBytes := bytes.NewReader(buffer)

                fileType := http.DetectContentType(buffer)

                path := "/media/" + file.Filename

                params := &s3.PutObjectInput{

                    Bucket:        aws.String("article-s3-jpskgc"),

                    Key:           aws.String(path),

                    Body:          fileBytes,

                    ContentLength: aws.Int64(size),

                    ContentType:   aws.String(fileType),

                }

                resp, err := svc.PutObject(params)


                fmt.Printf("response %s", awsutil.StringValue(resp))


                imageName.NAME = file.Filename


                imageNames = append(imageNames, imageName)

            }


            c.JSON(http.StatusOK, imageNames)

        })



查看完整回答
反对 回复 2023-07-04
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信