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 :: export csv in react 
Javascript :: covid-19 
Javascript :: encrypt decrypt javascript 
Javascript :: tolocaledatestring format dd-mm-yyyy 
Javascript :: electron hide devtools 
Javascript :: get function parameters count javascript 
Javascript :: js generate random string of length 
Javascript :: change root color js 
Javascript :: change port react app 
Javascript :: list javascript 
Javascript :: javascript loop backwards through array 
Javascript :: jquery form serialize object 
Javascript :: js remove html element 
Javascript :: hashing in node js 
Javascript :: axios how to get error response 
Javascript :: array map destructuring 
Javascript :: react native header 
Javascript :: angular disable click 
Javascript :: conditional array element js 
Javascript :: angularjs change route js 
Javascript :: js capitalize first letter of each word 
Javascript :: javascript indexof with condition 
Javascript :: check if object has method javascript 
Javascript :: adjacent elements product javascript 
Javascript :: jest input value 
Javascript :: react router get data from url 
Javascript :: javascript if value is a string function 
Javascript :: joi unique validation 
Javascript :: how set defualt image for dropify 
Javascript :: mysql remove quote on json extract 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =