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,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么