Answer the question
In order to leave comments, you need to log in
How to upload files from browser js + ajax + nodejs?
Colleagues good day,
I ask the experts for help, how to upload files and save them on the server, on the disk ???
Nodejs project.
png, jpeg, jpg, pdf files. Accordingly, you need to determine the type of file, its name and size, and then also save it to yourself. The task is apparently trivial, but I ran into it and can not solve it.
here is the html:
<form name="uploadMatricula" enctype="multipart/form-data" method="POST">
<label class="tramite">
Загрузить
<input type="file" id="matriculaFile" name="myfile" accept=".jpg,.jpeg,.png,.pdf" multiple>
</label>
</form>
let input = document.getElementById('upload');
input.addEventListener('change', () => {
let files = input.files;
let wrong = false;
if (files.length !== 1) {
this.eventEmitter.emit('popupManager:showTooltip', 'Можно грузить только один файл!');
return;
}
if (!this.checkFileFormat(files[0])) {
this.eventEmitter.emit('popupManager:showTooltip', 'Не верный формат файла!');
return;
}
if (files[0].size > this.fileSizeLimit) {
this.eventEmitter.emit('popupManager:showTooltip', 'Слишком большой файл, не больше 20мб грузите!');
return;
}
let fileData = {
name: files[0].name,
size: files[0].size,
type: files[0].type
}
let form_data = new FormData();
form_data.append('file', files[0]);
transport.uploadFile(form_data, files[0].type, (result) => {
console.log(result);
});
});
static uploadFile(fileData, header, callback) {
let xhr = new XMLHttpRequest();
xhr.open("POST", '/api/upload', true);
xhr.setRequestHeader('Content-Type', header);
xhr.send(fileData);
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
if (xhr.status >= 200 && xhr.status < 400) {
let json = (xhr.responseText !== '') ? JSON.parse(xhr.responseText) : '';
callback(json);
} else callback();
}
}
Answer the question
In order to leave comments, you need to log in
duplicate and comments above
mime-types
Mime-type file in Node.js
and to save busboy
-----
another solution
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question