我还在试着接受这件事。
我可以让用户选择文件(甚至多个)与文件输入:
<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 */);
这是一个带有注释的基本示例。上传功能就是你要找的:
// 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);
要提交单个文件,你可以直接使用输入的.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类型之一。
这是我的代码:
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>
这里公认的答案有点过时了。截至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);
});
添加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);