这是$ajax的写法
那类似这样的怎么写,网上实在是找不到了,那类似这样的怎么写,网上实在是找不到了
拿走不用客气
function uploadFile(url, file, onProgress, onSuccess, onError) {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
xhr.open('POST', url, true);
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = event.loaded / event.total * 100;
onProgress(percentComplete);
}
};
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
onSuccess(xhr.responseText);
} else {
onError(new Error('Upload failed with status ' + xhr.statusText));
}
};
xhr.onerror = function() {
onError(new Error('Upload failed with status ' + xhr.statusText));
};
xhr.send(formData);
}
// 使用方法
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
uploadFile(
'/upload',
file,
function(progress) {
console.log('Upload progress: ' + progress + '%');
},
function(responseText) {
console.log('Upload complete: ' + responseText);
},
function(error) {
console.error('Upload failed: ' + error.message);
}
);
});