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 :: remove id from array javascript 
Javascript :: how to make an event listener only work once 
Javascript :: js is variable int 
Javascript :: object.entries in javascript 
Javascript :: button disable in js 
Javascript :: set array length js 
Javascript :: react chunk file too large 
Javascript :: clone aJavaScript object 
Javascript :: JavaScript POSITIVE_INFINITY 
Javascript :: how to make a dictionary javascript 
Javascript :: sequelize transaction config 
Javascript :: javascript timestamp 
Javascript :: javascript array sorting 
Javascript :: infinite scroll for chat react js 
Javascript :: javascript span style 
Javascript :: react-data-table-component cell action 
Javascript :: array.push multiple 
Javascript :: flatten nested object 
Javascript :: get node degree networkx 
Javascript :: how to compare previous value with current in jquery 
Javascript :: time stamp to date js 
Javascript :: which line will generate a random number between 1 to 10 javascript 
Javascript :: react router switch 
Javascript :: ping discord with autocode 
Javascript :: send audio with socket io node js 
Javascript :: move last element of array to beginning javascript 
Javascript :: input show validation message 
Javascript :: route guard in react js 
Javascript :: how to set expire time of jwt token in node js 
Javascript :: create method javascript 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =