我还在试着接受这件事。

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

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

我可以用<填充事件处理程序>来捕获提交事件。但是一旦我这样做了,我如何使用fetch发送文件?

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

当前回答

这里公认的答案有点过时了。截至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);
});

其他回答

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

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

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

我们需要忽略Fetch请求的内容类型头。然后浏览器会自动添加内容类型头,包括表单边界,看起来像

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

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

要提交单个文件,你可以直接使用输入的.files数组中的file对象作为fetch()初始化器中body:的值:

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],
});

这是因为File继承自Blob,而Blob是在Fetch标准中定义的允许的BodyInit类型之一。

添加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);

    }
}

这就是php:

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

我是这样做的:

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