Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jsfetchapi上传文件?_Javascript_Fetch Api - Fatal编程技术网

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

我是这样做的:

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标准中定义的允许类型之一。

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

从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所指向的位置

这是我的代码:

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

最好添加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。这应该是正确的答案。另一种方法也可以,但更复杂你说的/化身是什么意思?您是指某个后端API端点吗?这是最简单的答案,但
body:myInput.files[0]
如何导致客户端内存中的字节数增加?我希望使用此解决方案,浏览器能够合理地流式处理文件,而不需要将其读入内存,@bhantol,但我并没有特意去发现(无论是从经验上还是通过深入研究规范)。如果您想确认,您可以尝试(在每个主要浏览器中)使用此方法上载50GB文件或其他内容,并查看您的浏览器是否尝试使用过多内存并导致死机。对我来说不起作用
express fileupload
无法分析请求流。但是
FormData
工作起来很有魅力。@attacomsian在我看来,
express fileupload
是一个服务器端库,用于处理包含文件的
multipart/form data
请求,所以是的,它与这种方法不兼容(它只是直接将文件作为请求体发送)。这是!非常重要!不要将自己的内容类型与多部分上的获取一起使用。我不知道为什么我的代码不工作。这是黄金!我浪费了1个小时不明白这一点。感谢分享此tipDownvote,因为尽管它是有用的信息,但这不会尝试回答OP的问题。这是非常重要的信息,未在中捕获。尝试某些答案失败后,官方文档对我有效:,可以确认:1。需要在FromData中包装文件;2.不需要在请求标题中声明
Content-Type:multipart/form-data
。这个示例为什么包括Content-Type标题,但另一个答案是在使用Fetch-API发送文件时忽略它们?哪一个?不要设置内容类型。我花了很多时间试图让它工作,然后发现这篇文章说不要设置它。而且它有效!您将如何从Express后端读取此文件。因为文件不是作为表单数据发送的。它只作为文件对象发送。express fileupload或multer是否解析此类有效载荷?fileinput是您单击上载的按钮的id吗?@sakib11 My node express server(在bodyParser.raw()的帮助下)只能在
内容类型
设置为
应用程序/x-www-form-urlencoded
的情况下接收此信息。来源:您好,请不要只回答源代码。试着提供一个关于你的解决方案如何工作的很好的描述。请参阅:。感谢使用
FormData
仅在服务器需要表单数据时才起作用。如果服务器需要一个r
$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);