如何使用html5 JS提取API上传文件?

我仍然试图围住它。

我可以让用户用文件inputselect文件(甚至多个文件):

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

而且我可以使用<fill in your event handler here>来捕获submit事件。 但是一旦我这样做,我该如何使用fetch发送文件?

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

我不知道我是否应该使用FileReader接口?

编辑:

我认为我在正确的方向,但不知道。 我从input type=file元素中获取文件,然后:

  const fr = new FileReader(); fr.readAsBinaryString(file); fr.addEventListener("loadend", function (evt) { http.fetch('/api/conversions',{ method: 'post', body: { input: evt.target.result } }).then(response => {}); }); 

我不确定我是否正确地做了这个?

这是一个基本和评论的例子, uploadfunction是你所寻找的:

 // 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 = (e) => { fetch('www.example.net', { // Your POST endpoint method: 'POST', headers: { "Content-Type": "You will perhaps need to define a content-type here" }, body: e.currentTarget.result // This is the content of your file }).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 = (files) => { // Files is a list because you can select several files // We just upload the first selected file const file = input.files[0]; const reader = new FileReader(); // We read the file and call the upload function with the result reader.onload = upload; reader.readAsText(file); }; // 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 })