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.
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,