How to Upload a File with the Js Fetch API

How do I upload a file with the JS fetch API?

This is a basic example with comments. The upload function is what you are looking for:

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

How can I upload file and also include JSON data with Fetch API?

you append it to FormData, not body

const uploadFile = ( e ) => {

const uploadedFile = e.target.files[ 0 ];
const formData = new FormData();
const str = 'from client';

formData.append( 'data', uploadedFile );
formData.append( 'str', str );

const rawResponse = await fetch( '/upload-file', {
method: 'POST',
body: formData
});

};

uploadFile();

how do I post form data and upload file with the JS fetch API

No need to transform to JSON, and no need to use entries() on FormData. Also check the spelling, you wrote formdata which is different than formData.

const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});

i am trying to upload a file using fetch API and formData - angular material

It worked when i do not add any headers.

 handleUpload(formData) {
const url = `/upload`;
const proxyurl = 'https://cors-anywhere-proxy.herokuapp.com/';
let result;
const req = new Request(proxyurl + url,
{
method: 'POST',
headers: {},
body: formData
});
fetch(req)
.then(response => response.text())
.then(() => {
if (result.data) {
console.log('result.data', result.data);
} else {
console.log('request failed');
}
})
.catch(() => console.log('Can\'t access ' + url + ' response. Blocked by browser?'));
}

react js fetch api using file upload not being sent to body

You cannot send a file in a JSON object in a request( atleast not without Base64 encoding it). Change your code in the following way to send a file with your form.

    let formData = new FormData(); 

// Update the formData object
formData.append(
"myFile",
this.state.product_picture,
this.state.product_picture.name
);

formData.append("product_name",this.state.product_name);
formData.append("product_description",this.state.product_description);
formData.append("category_name",this.state.category_choosen);

var options = { content: formData };
const token = JSON.parse(localStorage.getItem('token'));
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
};
fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
.then(response => response.json())
.then(data => {
this.setState({ product: data.product})
})
.catch(error =>{
console.log("Product creation error", error);
});

Send file to (fetch to c# web api)

1.[FromBody] is used receive application/json data. You need change [FromBody] to [FromForm]

2.To upload files using fetch and FormData.you must not set Content-Type header.

Whole working demo below:

let data = new FormData();
data.append('file', file);
const response = fetch('https://localhost:7054/Pictures',
{
method: 'POST',
body: data
});

Api controller:

[HttpPost]
public async Task<ActionResult> Index([FromForm] IFormFile file)
{
//.....
}

How to upload file using fetch

I'll answer my own question. If anyone else comes across this problem, it is the BACKEND that's faulty. This is my final solution using busboy to handle incoming form data. I didn't change anything on my server, but my router had to be updated. Here is my router, taking care of POST requests:

const express = require("express");
const mongoose = require("mongoose");
require('./../../models/Test');
const path = require("path");
const fs = require("fs");
const router = express.Router();

const Busboy = require("busboy");

router.route("/add").post((req, res, next) => {
let busboy = new Busboy({headers: req.headers});

// A field was recieved
busboy.on('field', function (fieldname, val, valTruncated, keyTruncated) {

if (req.body.hasOwnProperty(fieldname)) { // Handle arrays
if (Array.isArray(req.body[fieldname])) {
req.body[fieldname].push(val);
} else {
req.body[fieldname] = [req.body[fieldname], val];
}
} else { // Else, add field and value to body
req.body[fieldname] = val;
console.log(req.body);
}
});

// A file was recieved
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log("File incoming: " + filename);
var saveTo = path.join('.', filename);
console.log('Uploading: ' + saveTo);
file.pipe(fs.createWriteStream(saveTo));
});

// We're done here boys!
busboy.on('finish', function () {
console.log('Upload complete');
res.end("That's all folks!");
});
return req.pipe(busboy);
});

module.exports = router;

Finally, my finished onStydyPlanUpload() function!

onStudyPlanUpload(files) {

const file = files[0];
let formData = new FormData();

formData.append("pdf", file, file.name);
formData.append("comments", "A really lit study plan!");
formData.append("approved", true);
formData.append("uploaded_by", "Melker's mamma");
formData.append("date_uploaded", new Date());
formData.append("university", "australian_national_university");

const HOST = "http://localhost";
const PORT = 4000;
axios.post(`${HOST}:${PORT}/test/add`, formData)
.then(res => console.log(res))
.catch(err => console.log(err))

}

Got help from: https://gist.github.com/shobhitg/5b367f01b6daf46a0287



Related Topics



Leave a reply



Submit