亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過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 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號