doufeinai6081 2018-12-04 10:52 采纳率: 0%
浏览 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,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?