Javascript 如何使用jsfetchapi上传文件?
我仍在努力想办法解决这个问题 我可以让用户使用文件输入选择文件(甚至多个):Javascript 如何使用jsfetchapi上传文件?,javascript,fetch-api,Javascript,Fetch Api,我仍在努力想办法解决这个问题 我可以让用户使用文件输入选择文件(甚至多个): <form> <div> <label>Select file to upload</label> <input type="file"> </div> <button type="submit">Convert</button> </form> 这是一个带有注释的基本示例。uplo
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
这是一个带有注释的基本示例。
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);
这是一个带有注释的基本示例。
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);
我是这样做的:
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
})
我是这样做的:
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
})
要提交单个文件,只需使用
输入的.files
数组中的对象直接作为主体:
的值,在获取()
初始值设定项中:
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
是Fetch标准中定义的允许类型之一。要提交单个文件,您只需使用输入的。files
数组中的对象直接作为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
是Fetch标准中定义的允许类型之一。使用Fetch API发送文件的重要注意事项
对于获取请求,需要省略内容类型
头。然后浏览器将自动添加内容类型
标题,包括表单边界,如下所示
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
表单边界是表单数据的分隔符使用Fetch API发送文件的重要注意事项
对于获取请求,需要省略内容类型
头。然后浏览器将自动添加内容类型
标题,包括表单边界,如下所示
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
表单边界是表单数据的分隔符如果需要多个文件,可以使用此
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
})
如果需要多个文件,可以使用此选项
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
})
从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 })
从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 })
我的问题是,我使用response.blob()来填充表单数据。显然,你至少不能用react native这样做,所以我用了
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch似乎能够识别该格式,并将文件发送到uri所指向的位置 我的问题是使用response.blob()填充表单数据。显然,你至少不能用react native这样做,所以我用了
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch似乎能够识别该格式,并将文件发送到uri所指向的位置 这是我的代码:
html:
const upload=(文件)=>{
console.log(文件);
取('http://localhost:8080/files/uploadFile', {
方法:“POST”,
//标题:{
////“内容处置”:“附件;名称='file';文件名='xml2.txt',
//“内容类型”:“多部分/表单数据;边界=BbC04y”//”多部分/混合;边界=gc0p4Jq0M2Yt08jU534c0p”//ή//多部分/表单数据
// },
body:file//这是您的文件对象
}).那么(
response=>response.json()//如果响应是json对象
).那么(
success=>console.log(success)//处理成功响应对象
).接住(
error=>console.log(error)//处理错误响应对象
);
//cvForm.submit();
};
const onSelectFile=()=>upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change',onSelectFile,false)代码>
上传
这是我的代码:
html:
const upload=(文件)=>{
console.log(文件);
取('http://localhost:8080/files/uploadFile', {
方法:“POST”,
//标题:{
////“内容处置”:“附件;名称='file';文件名='xml2.txt',
//“内容类型”:“多部分/表单数据;边界=BbC04y”//”多部分/混合;边界=gc0p4Jq0M2Yt08jU534c0p”//ή//多部分/表单数据
// },
body:file//这是您的文件对象
}).那么(
response=>response.json()//如果响应是json对象
).那么(
success=>console.log(success)//处理成功响应对象
).接住(
error=>console.log(error)//处理错误响应对象
);
//cvForm.submit();
};
const onSelectFile=()=>upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change',onSelectFile,false)代码>
上传
这里公认的答案有点过时了。截至2020年4月,MDN网站上推荐的方法建议使用FormData
,也不要求设置内容类型
为了方便起见,我引用了代码片段:
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);
});
这里公认的答案有点过时。截至2020年4月,MDN网站上推荐的方法建议使用FormData
,也不要求设置内容类型
为了方便起见,我引用了代码片段:
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);
最好添加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);
如果上载的只是文件(这正是原始问题所需要的),则不需要将文件内容包装在FormData
对象中fetch
将接受input.files[0]
作为其主体
参数。如果您有一个PHP后端处理文件上载,您将希望将文件包装在FormData中,以便正确填充$\u文件数组。我还注意到,由于某种原因,Google Chrome不会在没有FormData部分的请求负载中显示文件。看起来像是谷歌Chrome网络面板上的一个bug。这应该是正确的答案。另一种方法也可以,但更复杂你说的/化身是什么意思?你是指某个后端吗