考虑这种形式:
<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>
还有这个 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>
它上传一个调用 Google Cloud Storage API 的文件:https://cloud.google.com/storage/docs/json_api/v1/objects/insert
但是,收到的文件如下所示:
内容:
------WebKitFormBoundaryZBAeI3W6nEzJeW7r--
类型:多部分/表单数据;边界=----WebKitFormBoundaryZBAeI3W6nEzJeW7r
我到底做错了什么?
另外,是否可以设置上传后立即刷新页面?
最佳答案
您将文件作为表单数据上传,它应该只是一个普通文件
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()); });
此外,您可能希望通过将按钮从提交按钮更改为普通按钮来阻止按下按钮时提交表单。 类型=“按钮”
关于javascript - 上传后文件内容错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49037326/