<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload a file</title>
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<link rel="icon" href="{% static 'images/favicon.png' %}">
</head>
<body class="container">
<form enctype="multipart/form-data" action="{% url 'upload' %}" method="post" class="my-md-5 mt-5 col-4"
style="display: none">
{% csrf_token %}
<input type="file" name="file" class="form-control form-inline btn-outline-primary btn" id="upload_file">
<input type="submit" id="submit">
</form>
<div>
<div class="form-inline">
<button id="file" class="btn btn-outline-primary mt-2 ml-5">选择文件</button>
<div class="form-text ml-3" id="info"></div>
</div>
<button id="upload" class="btn btn-outline-primary mt-2 ml-5">上传</button>
</div>
<div class="alert"></div>
</body>
<script>
document.getElementById("upload_file").onchange = function () {
let filename = document.getElementById("upload_file").value;
if (filename) {
let temp = '';
if (filename.includes("\\"))
temp = filename.split('\\');
else {
temp = filename.split("/");
}
document.getElementById("info").innerHTML = temp[temp.length - 1]
} else {
document.getElementsByClassName("text-info")[0].innerHTML = "";
}
};
document.getElementById("file").onclick = function () {
document.getElementById("upload_file").click();
};
document.getElementById("upload").onclick = function () {
if (document.getElementById("upload_file").value) { // 如果其中有文件
document.getElementById("submit").click();
} else {
let al = document.getElementsByClassName("alert")[0];
let html = "";
html += "<div class='alert alert-warning'>请选择需要上传的文件</div>";
al.innerHTML = html;
}
}
</script>
</html>
主要思想:
将form
表单隐藏,用其他的控件来间接的控制其中的input
效果: