I am still trying to wrap my head around it.
I can have the user select the file (or even multiple) with the file input:
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
I've done it like this:
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
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);
An important note for sending Files with Fetch API
One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Form boundary is the delimiter for the form data
If you want multiple files, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('/avatars', {
method: 'POST',
body: data
})
To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.
The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'm quoting the code snippet for convenience:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
It would be nice to add php endpoint example.
So that is js:
const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);
async function uploadFile(){
const formData = new FormData();
formData.append('nameusedinFormData',uploadinput.files[0]);
try{
const response = await fetch('server.php',{
method:'POST',
body:formData
} );
const result = await response.json();
console.log(result);
}catch(e){
console.log(e);
}
}
That is php:
$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
Here is my code:
html:
const upload = (file) => {
console.log(file);
fetch('http://localhost:8080/files/uploadFile', {
method: 'POST',
// headers: {
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data
// },
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
);
//cvForm.submit();
};
const onSelectFile = () => upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change', onSelectFile, false);
<form id="cv_form" style="display: none;"
enctype="multipart/form-data">
<input id="uploadCV" type="file" name="file"/>
<button type="submit" id="upload_btn">upload</button>
</form>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>
</ul>
How to upload a single file on select using HTML5 fetch
<label role="button">
Upload a picture
<input accept="image/*" type="file" hidden />
</label>
const input = document.querySelector(`input[type="file"]`);
function upload() {
fetch(uplaodURL, { method: "PUT", body: input.files[0] });
}
input.addEventListener("change", upload);
Related
I am still trying to wrap my head around it.
I can have the user select the file (or even multiple) with the file input:
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
I've done it like this:
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
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);
An important note for sending Files with Fetch API
One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Form boundary is the delimiter for the form data
If you want multiple files, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('/avatars', {
method: 'POST',
body: data
})
To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.
The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'm quoting the code snippet for convenience:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
It would be nice to add php endpoint example.
So that is js:
const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);
async function uploadFile(){
const formData = new FormData();
formData.append('nameusedinFormData',uploadinput.files[0]);
try{
const response = await fetch('server.php',{
method:'POST',
body:formData
} );
const result = await response.json();
console.log(result);
}catch(e){
console.log(e);
}
}
That is php:
$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
Here is my code:
html:
const upload = (file) => {
console.log(file);
fetch('http://localhost:8080/files/uploadFile', {
method: 'POST',
// headers: {
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data
// },
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
);
//cvForm.submit();
};
const onSelectFile = () => upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change', onSelectFile, false);
<form id="cv_form" style="display: none;"
enctype="multipart/form-data">
<input id="uploadCV" type="file" name="file"/>
<button type="submit" id="upload_btn">upload</button>
</form>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>
</ul>
How to upload a single file on select using HTML5 fetch
<label role="button">
Upload a picture
<input accept="image/*" type="file" hidden />
</label>
const input = document.querySelector(`input[type="file"]`);
function upload() {
fetch(uplaodURL, { method: "PUT", body: input.files[0] });
}
input.addEventListener("change", upload);
Using raw HTML when I post a file to a flask server using the following I can access files from the flask request global:
<form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
<input type="file" id="file" name="file">
<input type=submit value=Upload>
</form>
In flask:
def post(self):
if 'file' in request.files:
....
When I try to do the same with Axios the flask request global is empty:
<form id="uploadForm" enctype="multipart/form-data" v-on:change="uploadFile">
<input type="file" id="file" name="file">
</form>
uploadFile: function (event) {
const file = event.target.files[0]
axios.post('upload_file', file, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
If I use the same uploadFile function above but remove the headers json from the axios.post method I get in the form key of my flask request object a csv list of string values (file is a .csv).
How can I get a file object sent via axios?
Add the file to a formData object, and set the Content-Type header to multipart/form-data.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Sample application using Vue. Requires a backend server running on localhost to process the request:
var app = new Vue({
el: "#app",
data: {
file: ''
},
methods: {
submitFile() {
let formData = new FormData();
formData.append('file', this.file);
console.log('>> formData >> ', formData);
// You should have a server side REST API
axios.post('http://localhost:8080/restapi/fileupload',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
console.log('SUCCESS!!');
})
.catch(function () {
console.log('FAILURE!!');
});
},
handleFileUpload() {
this.file = this.$refs.file.files[0];
console.log('>>>> 1st element in files array >>>> ', this.file);
}
}
});
https://codepen.io/pmarimuthu/pen/MqqaOE
If you don't want to use a FormData object (e.g. your API takes specific content-type signatures and multipart/formdata isn't one of them) then you can do this instead:
uploadFile: function (event) {
const file = event.target.files[0]
axios.post('upload_file', file, {
headers: {
'Content-Type': file.type
}
})
}
Sharing my experience with React & HTML input
Define input field
<input type="file" onChange={onChange} accept ="image/*"/>
Define onChange listener
const onChange = (e) => {
let url = "https://<server-url>/api/upload";
let file = e.target.files[0];
uploadFile(url, file);
};
const uploadFile = (url, file) => {
let formData = new FormData();
formData.append("file", file);
axios.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
fnSuccess(response);
}).catch((error) => {
fnFail(error);
});
};
const fnSuccess = (response) => {
//Add success handling
};
const fnFail = (error) => {
//Add failed handling
};
This works for me, I hope helps to someone.
var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
.then(res => {
console.log({res});
}).catch(err => {
console.error({err});
});
this is my way:
var formData = new FormData(formElement);
// formData.append("image", imgFile.files[0]);
const res = await axios.post(
"link-handle",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
How to post file using an object in memory (like a JSON object):
import axios from 'axios';
import * as FormData from 'form-data'
async function sendData(jsonData){
// const payload = JSON.stringify({ hello: 'world'});
const payload = JSON.stringify(jsonData);
const bufferObject = Buffer.from(payload, 'utf-8');
const file = new FormData();
file.append('upload_file', bufferObject, "b.json");
const response = await axios.post(
lovelyURL,
file,
headers: file.getHeaders()
).toPromise();
console.log(response?.data);
}
There is an issue with Axios version 0.25.0 > to 0.27.2 where FormData object in a PUT request is not handled correctly if you have appended more than one field but is fine with one field containing a file, POST works fine.
Also Axios 0.25.0+ automatically sets the correct headers so there is no need to specify Content-Type.
For me the error was the actual parameter name in my controller... Took me a while to figure out, perhaps it will help someone. Im using Next.js / .Net 6
Client:
export const test = async (event: any) => {
const token = useAuthStore.getState().token;
console.log(event + 'the event')
if (token) {
const formData = new FormData();
formData.append("img", event);
const res = await axios.post(baseUrl + '/products/uploadproductimage', formData, {
headers: {
'Authorization': `bearer ${token}`
}
})
return res
}
return null
}
Server:
[HttpPost("uploadproductimage")]
public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
{
return Ok();
}
Error here because server is expecting param "image" and not "img:
formData.append("img", event);
public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
I am still trying to wrap my head around it.
I can have the user select the file (or even multiple) with the file input:
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
I've done it like this:
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
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);
An important note for sending Files with Fetch API
One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Form boundary is the delimiter for the form data
If you want multiple files, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('/avatars', {
method: 'POST',
body: data
})
To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.
The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'm quoting the code snippet for convenience:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
It would be nice to add php endpoint example.
So that is js:
const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);
async function uploadFile(){
const formData = new FormData();
formData.append('nameusedinFormData',uploadinput.files[0]);
try{
const response = await fetch('server.php',{
method:'POST',
body:formData
} );
const result = await response.json();
console.log(result);
}catch(e){
console.log(e);
}
}
That is php:
$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
Here is my code:
html:
const upload = (file) => {
console.log(file);
fetch('http://localhost:8080/files/uploadFile', {
method: 'POST',
// headers: {
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data
// },
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
);
//cvForm.submit();
};
const onSelectFile = () => upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change', onSelectFile, false);
<form id="cv_form" style="display: none;"
enctype="multipart/form-data">
<input id="uploadCV" type="file" name="file"/>
<button type="submit" id="upload_btn">upload</button>
</form>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>
</ul>
How to upload a single file on select using HTML5 fetch
<label role="button">
Upload a picture
<input accept="image/*" type="file" hidden />
</label>
const input = document.querySelector(`input[type="file"]`);
function upload() {
fetch(uplaodURL, { method: "PUT", body: input.files[0] });
}
input.addEventListener("change", upload);
I am still trying to wrap my head around it.
I can have the user select the file (or even multiple) with the file input:
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
I've done it like this:
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
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);
An important note for sending Files with Fetch API
One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Form boundary is the delimiter for the form data
If you want multiple files, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('/avatars', {
method: 'POST',
body: data
})
To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.
The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'm quoting the code snippet for convenience:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
It would be nice to add php endpoint example.
So that is js:
const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);
async function uploadFile(){
const formData = new FormData();
formData.append('nameusedinFormData',uploadinput.files[0]);
try{
const response = await fetch('server.php',{
method:'POST',
body:formData
} );
const result = await response.json();
console.log(result);
}catch(e){
console.log(e);
}
}
That is php:
$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
Here is my code:
html:
const upload = (file) => {
console.log(file);
fetch('http://localhost:8080/files/uploadFile', {
method: 'POST',
// headers: {
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data
// },
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
);
//cvForm.submit();
};
const onSelectFile = () => upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change', onSelectFile, false);
<form id="cv_form" style="display: none;"
enctype="multipart/form-data">
<input id="uploadCV" type="file" name="file"/>
<button type="submit" id="upload_btn">upload</button>
</form>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>
</ul>
How to upload a single file on select using HTML5 fetch
<label role="button">
Upload a picture
<input accept="image/*" type="file" hidden />
</label>
const input = document.querySelector(`input[type="file"]`);
function upload() {
fetch(uplaodURL, { method: "PUT", body: input.files[0] });
}
input.addEventListener("change", upload);
I am still trying to wrap my head around it.
I can have the user select the file (or even multiple) with the file input:
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
I've done it like this:
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
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);
An important note for sending Files with Fetch API
One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
Form boundary is the delimiter for the form data
If you want multiple files, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('/avatars', {
method: 'POST',
body: data
})
To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.
The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'm quoting the code snippet for convenience:
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
It would be nice to add php endpoint example.
So that is js:
const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);
async function uploadFile(){
const formData = new FormData();
formData.append('nameusedinFormData',uploadinput.files[0]);
try{
const response = await fetch('server.php',{
method:'POST',
body:formData
} );
const result = await response.json();
console.log(result);
}catch(e){
console.log(e);
}
}
That is php:
$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
Here is my code:
html:
const upload = (file) => {
console.log(file);
fetch('http://localhost:8080/files/uploadFile', {
method: 'POST',
// headers: {
// //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",
// "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data
// },
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
);
//cvForm.submit();
};
const onSelectFile = () => upload(uploadCvInput.files[0]);
uploadCvInput.addEventListener('change', onSelectFile, false);
<form id="cv_form" style="display: none;"
enctype="multipart/form-data">
<input id="uploadCV" type="file" name="file"/>
<button type="submit" id="upload_btn">upload</button>
</form>
<ul class="dropdown-menu">
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>
</ul>
How to upload a single file on select using HTML5 fetch
<label role="button">
Upload a picture
<input accept="image/*" type="file" hidden />
</label>
const input = document.querySelector(`input[type="file"]`);
function upload() {
fetch(uplaodURL, { method: "PUT", body: input.files[0] });
}
input.addEventListener("change", upload);