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

dei*_*tch 143 javascript fetch-api

我仍然试图绕过它.

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

<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>
Run Code Online (Sandbox Code Playgroud)

我可以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 */);
Run Code Online (Sandbox Code Playgroud)

小智 186

我这样做了:

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
})
Run Code Online (Sandbox Code Playgroud)

  • 如果您上传的所有内容都是文件(这是原始问题所需要的),则无需将文件内容包装在`FormData`对象中.`fetch`将接受`input.files [0]`作为其`body`参数. (13认同)
  • 如果你有一个处理文件上传的PHP后端,你需要将文件包装在FormData中,以便正确填充$ _FILES数组. (12认同)
  • 这应该是正确的答案.另一种方式也有效,但更复杂 (3认同)
  • 我还注意到,由于某种原因,如果没有FormData部分,Google Chrome不会在请求有效负载中显示文件。似乎是Google Chrome的“网络”面板中的错误。 (2认同)

Dam*_*ien 107

这是带注释的基本示例.该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);
Run Code Online (Sandbox Code Playgroud)

  • 为什么此示例中包含Content-Type标头,但另一个答案说要在使用Fetch API发送文件时忽略它们?哪一个? (5认同)
  • 不要设置Content-Type。我花了很多时间尝试使其工作,然后发现这篇文章说不要设置它。而且有效!https://muffinman.io/uploading-files-using-fetch-multipart-form-data/ (5认同)
  • 其他人只在服务器端得到一个空对象吗? (3认同)

mad*_*313 68

使用Fetch API发送文件的重要注意事项

需要省略 content-typeFetch请求的标头.然后浏览器将自动添加Content type包含表格边界的标题

Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Run Code Online (Sandbox Code Playgroud)

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

  • 这个!很重要!不要在multipart上使用自己的内容类型和fetch.我不知道为什么我的代码不起作用. (11认同)
  • [获取 - multipart/form-data POST 中缺少边界](/sf/ask/2749630691/) (2认同)
  • 这是黄金!我浪费了 1 小时不理解这一点。感谢分享这个技巧 (2认同)
  • 拒绝投票,因为即使它是有用的信息,但这并不试图回答 OP 的问题。 (2认同)
  • 这是非常重要的信息,未在[MDN Fetch docs](https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#Uploading_a_file)中捕获。 (2认同)

Ale*_*oya 28

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

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
})
Run Code Online (Sandbox Code Playgroud)

  • 请注意,不需要显式传递 `file.name` 作为文件名;根据 [MDN 文档 on `FormData.append`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/append),`File` 对象的默认名称已经是文件的文件名。 (2认同)

Mar*_*ery 16

要提交一个文件,你可以简单地使用File对象从input.files阵列作为直接的价值body:在你的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],
});
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为它File继承自Fetch标准中定义的允许类型Blob,并且Blob是其中一种BodyInit.

  • 我希望*通过这个解决方案,浏览器将足够合理地流式传输文件而不需要将其读入内存,@ bhantol,但我并没有尽力找出答案(无论是凭经验还是通过深入研究规范).如果你想确认一下,你可以尝试(在每个主流浏览器中)使用这种方法上传50GB文件或其他东西,看看你的浏览器是否试图使用太多内存并被杀死. (2认同)

Rai*_*yan 15

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

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

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);
});
Run Code Online (Sandbox Code Playgroud)

  • 仅当服务器需要表单数据时,使用“FormData”才有效。如果服务器想要一个原始文件作为 POST 的正文,则接受的答案是正确的。 (4认同)

小智 10

最好添加 php 端点示例。所以这就是js:

const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);

async function uploadFile(){
    const formData = new FormData();
    formData.append('nameusedinFormData',uploadinput.files[0]);    
    try{
        const response = await fetch('server.php',{
            method:'POST',
            body:formData
        } );
        const result = await response.json();
        console.log(result);
    }catch(e){
        console.log(e);

    }
}
Run Code Online (Sandbox Code Playgroud)

那就是php:

$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
Run Code Online (Sandbox Code Playgroud)

  • 该问题没有假设用于上传文件的后端技术。 (6认同)

小智 5

借鉴 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 })
Run Code Online (Sandbox Code Playgroud)