用input type="file"选择图片后确定如何自动转跳
时间: 2024-05-06 07:20:21 浏览: 7
自动跳转到哪里?可以使用JavaScript来实现选择图片后自动跳转到指定的页面。
例如,假设要将选择的图片上传到服务器上并在上传成功后跳转到另一个页面,可以使用以下代码:
HTML代码:
```
<input type="file" id="uploadImg">
<button onclick="upload()">上传</button>
```
JavaScript代码:
```
function upload() {
var fileInput = document.getElementById("uploadImg");
var file = fileInput.files[0];
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
window.location.href = "success.html"; // 上传成功后跳转到success.html页面
} else {
alert("上传失败");
}
}
};
xhr.open("POST", "upload.php");
xhr.send(formData);
}
```
在上面的代码中,当点击“上传”按钮时,会调用upload()函数。该函数首先获取选择的图片文件,然后使用FormData将图片文件添加到请求中。接着,使用XMLHttpRequest发送POST请求到服务器上的upload.php文件,upload.php文件会将图片保存到服务器上。当上传成功后,会自动跳转到success.html页面。