html - 使用 HTML 表单同时提交数据和文件
问题描述
我正在尝试获取一些用户输入并让用户同时上传文件。这可以做到吗?我在下面发布我的 HTML 文件内容。问题是 enctype 参数。当设置为 multipart/form-data 时,它不接受通常的文本字段。如果删除,它可以工作。
HTML 表单:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>UI_Automation</title>
</head>
<body>
<form action = "DataBridge" method = "POST" ><!-- enctype = "multipart/form-data" -->
Select area for automation :
<select id="section" name = "section_select">
<option value = "Section1" selected>UPI</option>
<option value = "Section2">Bank</option>
</select>
Select OS Type :
<select id="os" name = "os_select">
<option value = "Android" selected>Android</option>
<option value = "iOS">iOS</option>
</select>
<!-- <h2>Upload Test cases:</h2>
Select an Excel file to upload: <br />
<input type = "file" id="testcase" name = "file" size = "50" />
<br /> -->
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
解决方案
这很容易。
在您的 HTML 中
<form id="applyform" method="POST">
<label>Name</label>
<input class="form-control" type="text" name="name" placeholder="Enter your name" id="c_name" required>
Attach your resume:
<input type="file" name="resume" id="resume" accept="application/pdf,application/vnd.ms-excel">
<button type="submit" class="btn btn-info2 btn-footer">Submit</button>
</form>
现在form-action中提到的JS函数
$('#applyform').on('submit', function (e) {
e.preventDefault();
var reader = new FileReader(),
file = $('#resume')[0];
if (!file.files.length) {
Toast('no file uploaded');
return false;
}
reader.onload = function () {
var data = reader.result,
base64 = data.replace(/^[^,]*,/, ''),
info = {
name: $('#c_name').val(),
resume: base64
};
$.ajax({
url: "submitApplication.php",
type: "POST",
dataType: "JSON",
data: info,
success: function (response) {
if (response.result == "successful") {
Toast("Application submitted successfully!");
resetForm();
setTimeout(function () {
window.location.replace("careers.html");
}, 2000);
} else {
Toast("Error uploading! Try after sometime.")
}
}
});
};
reader.readAsDataURL(file.files[0]);
});
奖励:限制文件上传大小。
var uploadField = document.getElementById("resume");
uploadField.onchange = function () {
if (this.files[0].size > 2097152) {
Toast("File must be less than 2mb!");
this.value = "";
};
};
推荐阅读
- css - 相同的 CSS 在具有 Chrome 的两台 PC 上具有不同的行为
- python - 在 sqlite3 中减少读取数据库冗余的功能
- javascript - 根据包括键名在内的值进行排序
- apache-spark - 有条件的 PySpark 窗口
- arrays - 在 Swift 中通过多个关键字过滤对象
- python - tensorflow:InvalidArgumentError 同时找到 AUC 分数
- java - Camel DynamicEndpoint toD 和 Http-Component 的问题
- javascript - 赫斯基 5 .huskey gitignore
- mapstruct - MapStruct:从多个变量映射到一个集合
- git - 将子文件夹推送到 GitHub,而不是父目录