Javascript 如何使用 JS fetch API 上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36067767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:36:06  来源:igfitidea点击:

How do I upload a file with the JS fetch API?

javascriptfetch-api

提问by deitch

I am still trying to wrap my head around it.

我仍然试图绕过它。

I can have the user select the file (or even multiple) with the file input:

我可以让用户使用文件输入选择文件(甚至多个):

<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>

And I can catch the submitevent using <fill in your event handler here>. But once I do, how do I send the file using fetch?

我可以submit使用<fill in your event handler here>. 但是一旦我这样做了,我如何使用 发送文件fetch

fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);

采纳答案by Damien

This is a basic example with comments. The uploadfunction is what you are looking for:

这是一个带有注释的基本示例。该upload功能是您正在寻找的功能:

// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');

// This will upload the file after having read it
const upload = (file) => {
  fetch('http://www.example.net', { // Your POST endpoint
    method: 'POST',
    headers: {
      // Content-Type may need to be completely **omitted**
      // or you may need something
      "Content-Type": "You will perhaps need to define a content-type here"
    },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);

// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);

回答by Integ

I've done it like this:

我是这样做的:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

回答by madhu131313

An important note for sending Files with Fetch API

使用 Fetch API 发送文件的重要说明

One needs to omit content-typeheader for the Fetch request. Then the browser will automatically add the Content typeheader including the Form Boundary which looks like

需要省略 content-typeFetch 请求的标头。然后浏览器会自动添加Content type包括表单边界的标题,它看起来像

Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

Form boundary is the delimiter for the form data

表单边界是表单数据的分隔符

回答by Alex Montoya

If you want multiple files, you can use this

如果你想要多个文件,你可以使用这个

var input = document.querySelector('input[type="file"]')

var data = new FormData()
for (const file of input.files) {
  data.append('files',file,file.name)
}

fetch('/avatars', {
  method: 'POST',
  body: data
})

回答by Mark Amery

To submit a single file, you can simply use the Fileobject from the input's .filesarray directly as the value of body:in your fetch()initializer:

要提交单个文件,您可以直接使用's数组中的File对象作为初始值设定项中的值:input.filesbody:fetch()

const myInput = document.getElementById('my-input');

// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
  method: 'POST',
  body: myInput.files[0],
});

This works because Fileinherits from Blob, and Blobis one of the permissible BodyInittypes defined in the Fetch Standard.

这是有效的,因为File继承自Blob,并且BlobBodyInitFetch 标准中定义的允许类型之一。

回答by Raiyan

The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormDataand also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

这里接受的答案有点过时了。截至 2020 年 4 月,在 MDN 网站上看到的推荐方法建议使用FormData并且也不要求设置内容类型。https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

I'm quoting the code snippet for convenience:

为方便起见,我引用了代码片段:

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then((response) => response.json())
.then((result) => {
  console.log('Success:', result);
})
.catch((error) => {
  console.error('Error:', error);
});

回答by Jerald Macachor

Jumping off from Alex Montoya's approach for multiple file input elements

从 Alex Montoya 的多个文件输入元素的方法中跳出来

const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();

for (const file of inputFiles) {
    formData.append(file.name, file.files[0]);
}

fetch(url, {
    method: 'POST',
    body: formData })

回答by NickJ

The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using

我的问题是我正在使用 response.blob() 来填充表单数据。显然你至少不能用 react native 做到这一点,所以我最终使用了

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch seems to recognize that format and send the file where the uri is pointing.

Fetch 似乎可以识别该格式并将文件发送到 uri 指向的位置。

回答by Andreas Patsimas

Here is my code:

这是我的代码:

html:

html:

const upload = (file) => {
    console.log(file);

    

    fetch('http://localhost:8080/files/uploadFile', { 
    method: 'POST',
    // headers: {
    //   //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",
    //   "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" //  ? // multipart/form-data 
    // },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );

  //cvForm.submit();
};

const onSelectFile = () => upload(uploadCvInput.files[0]);

uploadCvInput.addEventListener('change', onSelectFile, false);
<form id="cv_form" style="display: none;"
          enctype="multipart/form-data">
          <input id="uploadCV" type="file" name="file"/>
          <button type="submit" id="upload_btn">upload</button>
</form>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>
</ul>