【问题标题】:How to upload a file using Gin + React?如何使用 Gin + React 上传文件?
【发布时间】:2021-03-17 01:44:12
【问题描述】:

我想从 React 上传一个图像文件,这样做似乎我需要将图像存储在服务器上并从 POST 请求中检索它,以便将其修改为 url 路径。

  • 使用 Gin Gonic http 框架。

这是我的 POST 请求在 React 中的表单:

    <form action="/upload" method="POST">
      <label htmlFor="upload" onChange={onChange}>
        <FontAwesomeIcon icon={faUserCircle} color="#3B5998" size="10x" className={`${pointer}`} />
        <input type="file" hidden id="upload" name="upload" />
      </label>
    </form>

这是我在onChange 中调用的方法,以将请求与图像文件一起发送:

  uploadFile = (file) => {
    const formData = new FormData();
    formData.append('image', file);
    axios({
      method: 'post',
      url: `${gamingApiBaseURL}/v1/upload-image`,
      data: formData,
      headers: { 'Content-Type': 'multipart/form-data' },
    }).catch((error) => {
      console.log('error storing image', error);
    });
  };

这是我的 Go 结构,用于绑定请求

type ImageForm struct {
    Image *multipart.FileHeader `form:"upload binding:"required"`
}

最后,应该获取图像文件并将其上传到服务器的方法。这是我到目前为止所拥有的。我收到一条错误消息 http: no such file,这很奇怪,因为在 Postman 中我看到了 image 键和文件名,我试图了解在 Go 中上传图像的工作原理。

func extractImage(c *gin.Context) {
    // Using 'ShouldBind'
    formFile, err := c.FormFile("image")

    fmt.Println("Error", err)
    if err != nil {
        c.JSON(http.StatusBadRequest, err)
    }

    fmt.Println("form error", formFile)
}

【问题讨论】:

  • 我认为我面临的问题是在 React 方面,正确转换表单数据以正确检索文件。在邮递员工作。
  • 删除{ 'Content-Type': 'multipart/form-data' }
  • 当我从文件系统上传 png/jpg 图像时,我仍然没有收到这样的文件。

标签: reactjs go go-gin


【解决方案1】:

我认为这个结构标签是错误的

type ImageForm struct {
    Image *multipart.FileHeader `form:"upload binding:"required"`
}

改成这个(upload后缺少双引号):

type ImageForm struct {
    Image *multipart.FileHeader `form:"upload" binding:"required"`
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-09
    • 2021-02-28
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多