case-uploads/client/index.js

125 lines
3.4 KiB
JavaScript

import axios from 'axios';
/*
* @Author: jukaifeng jukaifeng@lingtu.com
* @Date: 2024-10-24 09:03:50
* @LastEditors: jukaifeng jukaifeng@lingtu.com
* @LastEditTime: 2024-10-24 13:51:16
* @FilePath: /case-uploads/client/index.js
* @Description:
*/
const el_file = document.querySelector('#file');
const el_btn = document.querySelector('#upload');
const el_file2 = document.querySelector('#file2');
const el_btn2 = document.querySelector('#upload2');
const el_file3 = document.querySelector('#file3');
const el_btn3 = document.querySelector('#upload3');
// form-data上传
el_btn.addEventListener('click', () => {
if (!el_file.value) {
alert('请选择文件');
return;
}
const file = el_file.files[0];
const formData = new FormData();
formData.append('file', file);
axios.post('http://localhost:3000/upload', formData, {
headers: {
'Content-Type': 'application/form-data'
}
}).then(res => {
console.log(res);
if (res.data.code === 'success') {
alert('上传成功');
el_file.value = '';
} else {
alert('上传失败');
el_file.value = '';
}
}).catch(err => {
console.error(err);
alert('上传失败');
el_file.value = '';
});
});
//base64上传
el_btn2.addEventListener('click', () => {
if (!el_file2.value) {
alert('请选择文件');
return;
}
const file = el_file2.files[0];
const ext = file.name.split('.').pop();
const reader = new FileReader();
reader.onload = (e) => {
const uint8Array = new Uint8Array(e.target.result);
const str = uint8Array.reduce((prev, byte) => {
return prev + String.fromCharCode(byte);
}, '');
const base64Data = btoa(str);
axios.post('http://localhost:3000/base64', {
ext,
file: base64Data
}).then(res => {
console.log(res);
if (res.data.code === 'success') {
alert('上传成功');
el_file2.value = '';
} else {
alert('上传失败');
el_file2.value = '';
}
}).catch(err => {
console.error(err);
alert('上传失败');
el_file2.value = '';
});
};
reader.readAsArrayBuffer(file);
});
//二进制上传
el_btn3.addEventListener('click', () => {
if (!el_file3.value) {
alert('请选择文件');
return;
}
const file = el_file3.files[0];
const ext = file.name.split('.').pop();
const reader = new FileReader();
reader.onload = () => {
const binaryData = reader.result;
console.log(ext);
axios.post('http://localhost:3000/binary', binaryData, {
headers: {
'Content-Type': 'application/octet-stream',
'x-ext': ext
}
}).then(res => {
console.log(res);
if (res.data.code === 'success') {
alert('上传成功');
el_file3.value = '';
} else {
alert('上传失败');
el_file3.value = '';
}
}).catch(err => {
console.error(err);
alert('上传失败');
el_file3.value = '';
});
};
reader.readAsArrayBuffer(file);
});