Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

uploading file with fetch

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

Using fetch to upload files

//fetch using a Request and a Headers objects
// uploading an image along with other POST data
//using jsonplaceholder for the data
//video tutorial https://youtu.be/JtKIcqZdLLM

const url = 'https://postman-echo.com/post';

document.addEventListener('DOMContentLoaded', init);

function init(){
    document.getElementById('btnSubmit').addEventListener('click', upload);
}

function upload(ev){
    ev.preventDefault();    //stop the form submitting

    //create any headers we want
    let h = new Headers();
    h.append('Accept', 'application/json'); //what we expect back
    //bundle the files and data we want to send to the server
    let fd = new FormData();
    fd.append('user-id', document.getElementById('user_id').value);
    
    let myFile = document.getElementById('avatar_img').files[0];
    fd.append('avatar', myFile, "avatar.png");
    // $_FILES['avatar']['file_name']  "avatar.png"
    let req = new Request(url, {
        method: 'POST',
        headers: h,
        mode: 'no-cors',
        body: fd
    });

    fetch(req)
        .then( (response)=>{
            document.getElementById('output').textContent = "Response received from server";
        })
        .catch( (err) =>{
            console.log('ERROR:', err.message);
        });
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: testing library react hooks 
Javascript :: ruby write json to file 
Javascript :: encrypt javascript node 
Javascript :: js get first element of array 
Javascript :: sapui5 get fragment by id 
Javascript :: how to ssh into gke node 
Javascript :: ajax file form 
Javascript :: how to change root variable css 
Javascript :: object destructuring javascript 
Javascript :: or inside if javascript 
Javascript :: how to use foreach in javascript 
Javascript :: javascript get phone number from string 
Javascript :: submit form using jquery 
Javascript :: get home dir in nodejs 
Javascript :: force rerender react 
Javascript :: read xlsx file in angular 5 
Javascript :: jquery sibling 
Javascript :: javascript encode base64 
Javascript :: function currying javascript 
Javascript :: hmac_sha256 node 
Javascript :: javascript set variable if not defined 
Javascript :: string json to class c# 
Javascript :: how to icon font-awesome react cart 
Javascript :: suppress spaces in front and in the end of a string javascript 
Javascript :: textinput multiline start from top react native 
Javascript :: javascript Get Key/Values of Map 
Javascript :: javascript pseudo random 
Javascript :: fetch Response object get content type 
Javascript :: expose deployment nodeport command 
Javascript :: classiceditor is not defined using npm 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =