Reputation: 13
Here I want to hit the api of the golang to upload a file on the local system using javascript. To get the key, value pair for file I read the FormData method in the javascript and I used it in my code but it will not taking the key, value while I'm assigning the data. I have posted my code.
function uploadFile(){
var url = "http://localhost:8081/shapi/v1/upload";
var archivoSeleccionado = document.getElementById("myfile");
var file = archivoSeleccionado.files[0];
var f = new FormData();
console.log(file)
f.append("file", file);
console.log("f", f)
var xmlHTTP= new XMLHttpRequest();
xmlHTTP.open("POST", url, true);
xmlHTTP.send(f);
}
In console of console.log(file)
it will print
File { name: "541660.jpg", lastModified: 1537849576000, webkitRelativePath: "", size: 243477, type: "image/jpeg" }
In console of console.log("f", f)
it will print:-
FormData { }
Can anyone tell me the problem in my code?
Runnable Snippet
function uploadFile() {
var archivoSeleccionado = document.getElementById("myfile");
var file = archivoSeleccionado.files[0];
var f = new FormData();
console.log(file)
f.append("file", file);
console.log("f", f)
}
<input id="myfile" type="file" />
<button onclick="uploadFile()">Upload</button>
Upvotes: 0
Views: 109
Reputation: 6739
It's only because when you log the FormData
it doesn't expose what it has on it by default, you have to explicitly get it, you can do this by using get(key)
or values()
function uploadFile() {
var archivoSeleccionado = document.getElementById("myfile");
var file = archivoSeleccionado.files[0];
var f = new FormData();
console.log(file)
f.append("file", file);
console.log("f", f.get("file"))
}
<input id="myfile" type="file" />
<button onclick="uploadFile()">Upload</button>
Upvotes: 1