SubZeno
SubZeno

Reputation: 380

Wrong file content after the upload

Consider this form:

<form class="well">
   <fieldset>
      <div class="form-group">
         <label for="exampleInputFile">File input</label><input id="exampleInputFile" type="file" aria-describedby="fileHelp" class="form-control-file">
      </div>
      <div class="form-group"><button type="submit" onclick="submitForm();" class="btn btn-info btn-sm pull-right">Submit</button></div>
   </fieldset>
</form>

And this javascript:

<script>
function submitForm() 
{
    console.log("Fetching the file...");
    var input = document.getElementById('input[type="file"]');
    var data = new FormData();
    data.append('file', input.files[0]);
    console.log(file.size);
    fetch('https://www.googleapis.com/upload/storage/v1/b/' + #{bucket} + '/o?uploadType=media&name=sample.txt', {
      method: 'POST',
      body: data
    }).then(function(res){ console.log(res.json()); });
}
</script>

It uploads a file invoking the Google Cloud Storage API: https://cloud.google.com/storage/docs/json_api/v1/objects/insert

However, the received file looks like that:

Content:

------WebKitFormBoundaryZBAeI3W6nEzJeW7r--

Type: multipart/form-data; boundary=----WebKitFormBoundaryZBAeI3W6nEzJeW7r

What am I actually doing wrong?

Also, is it possible to set up a page refresh right after the upload?

Upvotes: 0

Views: 193

Answers (1)

Musa
Musa

Reputation: 97672

You uploaded the file as form data, it should just be a plain file

fetch('https://www.googleapis.com/upload/storage/v1/b/' + #{bucket} + '/o?uploadType=media&name=sample.txt', {
  method: 'POST',
  body: input.files[0]
}).then(function(res){ console.log(res.json()); });

Also you might want to prevent the form from submitting when you push the button by changing the button from a submit button to a normal button. type="button"

Upvotes: 2

Related Questions