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)
})
- 1 回答
- 0 关注
- 138 浏览
添加回答
举报