gpt4 book ai didi

javascript - 使用带有进度条和附加字段的核心 JavaScript 进行 Ajax 文件上传

转载 作者:行者123 更新时间:2023-12-02 23:49:32 25 4
gpt4 key购买 nike

我们如何使用带有一些附加参数和进度条的ajax请求上传文件。

最佳答案

我们可以使用核心 JavaScript 和 XHR 发出 ajax 请求来上传文件。创建以下文件:

/* ** upload.js ** */
var submit = document.getElementById('submit'),
file = document.getElementById('file'),
title = document.getElementById('title');
progress = document.getElementById('progress');

var upload = function(){

if(file.files.length === 0){
return;
}

var data = new FormData();
data.append('title', title.value);
data.append('SelectedFile', file.files[0]);

var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};

request.upload.addEventListener('progress', function(e){
var progress_width = Math.ceil(e.loaded/e.total * 100) + '%';
progress.style.width = progress_width;
}, false);

request.open('POST', 'save.php');
request.send(data);
}

submit.addEventListener('click', upload);
/* ** style.css ** */
.container {
width: 500px;
margin: 0 auto;
}
.progress_outer {
border: 1px solid #000;
}
.progress {
width: 0%;
background: #DEDEDE;
height: 20px;
}
<!-- ** index.html ** -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS File Upload with Progress</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class='container'>
<p>
Enter Title: <input type='text' id='title'>
</p>
<br/>
<p>
Select File: <input type='file' id='file'>
</p>
<br/>
<input type='button' id='submit' value='Upload File'>
<div class='progress_outer'>
<div id='progress' class='progress'></div>
</div>
</div>
<script src='upload.js'></script>
</body>
</html>

通过运行上面的代码,您将在 php 文件中获得文件和标题字段值,如下所示:

print_r($_FILES);   // for get file
print_r($_REQUEST); // for get additional fields

输出

Array
(
[SelectedFile] => Array
(
[name] => 3400_1_1552283374.pdf
[type] => application/pdf
[tmp_name] => D:\xamp\tmp\php6D08.tmp
[error] => 0
[size] => 500320
)

)
Array
(
[title] => title
)

关于javascript - 使用带有进度条和附加字段的核心 JavaScript 进行 Ajax 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com