【问题标题】:Wrong file content after the upload上传后文件内容错误
【发布时间】:2018-08-08 18:59:30
【问题描述】:

考虑这种形式:

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

输入:multipart/form-data; boundary=----WebKitFormBoundaryZBAeI3W6nEzJeW7r

我到底做错了什么?

另外,是否可以在上传后立即设置页面刷新?

【问题讨论】:

    标签: javascript jquery google-cloud-platform google-cloud-storage


    【解决方案1】:

    您将文件作为表单数据上传,它应该只是一个普通文件

    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()); });
    

    此外,您可能希望通过将按钮从提交按钮更改为普通按钮来防止在按下按钮时提交表单。 type="button"

    【讨论】:

    • 如何通过这种方式获取文件大小和mime类型?
    • 大小input.files[0].size,mime类型input.files[0].type
    • 太好了,现在上传效果很好。只有一件事:我无法获得响应正文 console.log(res.json()) 没有在控制台中显示内容。
    • 你从console.log(res)得到什么?
    • 我确实尝试过:... }).then(function(res){ console.log('test!'); });,但控制台内没有出现任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多