“Usando o Fetch para fazer upload de arquivos” Respostas de código

Faça o upload do arquivo com busca

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

Usando o Fetch para fazer upload de arquivos

//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);
        });
}
Meandering Meerkat

Respostas semelhantes a “Usando o Fetch para fazer upload de arquivos”

Perguntas semelhantes a “Usando o Fetch para fazer upload de arquivos”

Mais respostas relacionadas para “Usando o Fetch para fazer upload de arquivos” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código