doufeinai6081 2018-12-04 10:52
浏览 42
已采纳

如何将文件从HTML选择器发送到Golang API?

I have an html file selector in my html code. I'm selecting an image from that selector and send it to the golang code via jquery. But the image file will not receiving by the golang code. I'm showing my html and golang code.

html:-

<input type="file" name="myFile" id="imageSelector"><br><br>
<button id="uploadImage">Upload Image</button>

jquery:-

$( document ).ready(function() {
    var inputFile = $('#imageSelector').val().split('\\').pop(); // give you file name
    $("#uploadImage").on("click", function(e){
        $.ajax({
            url: "/api/v1/upload",
            type: "POST",
            contentType: false,
            processData: false,
            data:{"file":inputFile},
            success: function(response){
                console.log(response);
            }
        });
    });
});

In golang code i'm receiving it by using gin package

func GetSelectedImage(c *gin.Context){
  file, err := c.FormFile("file")
  fmt.Pritnln(file) //it will show nothing
  fmt.Println(err) // request Content-Type isn't multipart/form-data
} 

Error:-

request Content-Type isn't multipart/form-data

Where is the error I'm doing. I can't change my golang code but html code is editable. Can anybody tell me what thing I'm doing wrong.

  • 写回答

1条回答 默认 最新

  • douyaju4749 2018-12-04 11:22
    关注

    You are passing data a plain object and telling jQuery not to process it.

    This means it just gets converted to the string [object Object] and jQuery sets the content-type to text/plain;charset=UTF-8.

    So it isn't multipart/form-data and it doesn't claim to be.


    Pass a FormData object instead, and pass it a file, not just file name.

    const data = new FormData();
    data.append("file", $("#imageSelector")[0].files[0], inputFile);
    // ...
    contentType: false,
    processData: false,
    data: data,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能