javascript - 使用带有进度条和附加字段的核心 JavaScript 上传 Ajax 文件
问题描述
我们如何使用带有一些附加参数和进度条的 ajax 请求上传文件。
解决方案
我们可以使用带有 XHR 的核心 JavaScript 发出 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
)
推荐阅读
- reactjs - 如果收到错误,如何从响应中获取数据?
- snowflake-cloud-data-platform - 使用 sqlalchemy 的雪花 sso 连接不起作用
- java - 使用 Hibernate 从 MS SQL 检索值时出错
- python - 我尝试使用 python 在 s3 空间上保存一个 mp3 文件但得到了空文件
- c# - Cosmos DB - 一些记录插入失败
- reinforcement-learning - 网格世界中的终端状态是什么?
- java - Spring Boot - 接口和一些功能实现
- python - 两个列表之间的距离相似度
- javascript - 使用 undescore.js,我正在尝试将给定的输入格式化为预期的输出
- sql - 如何在 Firebird 的限制视图上授予用户 SELECT