提交表单代码:
<form action="#" method="POST" enctype="multipart/form-data" id="upload-form">
<label for="file">选择一个图像文件:</label>
<input type="file" id="file" name="file" accept="image/*"><br>
<input type="submit" value="上传">
<div class="status" id="status"></div>
</form>
JavaScript提交代码:
<script>
const form = document.getElementById('upload-form');
const status = document.getElementById('status');
form.addEventListener('submit', event => {
event.preventDefault();
status.style.display = 'none';
const fileInput = document.getElementById('file');
const file = fileInput.files[0];
if (!file) {
showError('Please choose a file to upload.');
return;
}
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
try {
const responseJson = JSON.parse(xhr.responseText);
const url = responseJson.url;
if (url) {
showSuccess(`图片网址 ${url}`);
} else {
showError('Failed to upload the image.');
}
} catch (error) {
showError('Failed to parse the response from the server.');
}
} else if (this.readyState === XMLHttpRequest.DONE) {
showError(`Server returned status code ${xhr.status}.`);
}
};
xhr.open('POST', 'https://api.suyanw.cn/huluxia/upload.php');
xhr.send(formData);
function showSuccess(message) {
status.textContent = message;
status.classList.remove('error');
status.classList.add('success');
status.style.display = 'block';
}
function showError(message) {
status.textContent = message;
status.classList.remove('success');
status.classList.add('error');
status.style.display = 'block';
}
});
</script>
相关专题
2021-10-10 1187
图床专题为您整理收藏本站所有关于图床相关详细资源,主要为各语言图床源码下载,各程序图床插件下载和图床上传工具软件下载....