如何解决在“选择文件”之后提供选项“添加更多文件”并列出提交表单之前选择的所有文件的名称
目标:选择“选择文件”按钮后,我想显示文件的名称(f1.txt 和 f2.txt)。在那之后,我希望能够再次单击该按钮并将它们与以前的按钮一起列出(f1.txt、f2.txt、f3.txt 和 f4.txt)。在点击“上传文件”之后,我想上传所有 4 个文件。
我试过隐藏前面的按钮,但在其他部分没有成功。我看到这篇似乎很有帮助的帖子:List selected files from file input。我已经研究了一个星期,并决定发布这个。
以下是代码供您参考。
附言我是这个领域的新手,所以请详细说明你的答案。(抱歉搞砸了)
function restrictTypeAndSize(obj) {
var s = true;
for (var i = 0; i < obj.files.length; i++) {
s = writefiles(obj.files[i]);
}
}
function writefiles(file) {
if (file.type.indexOf("image") == -1 && file.type.indexOf("pdf") == -1) {
alert("Invalid Type!");
$("#fileAttachment").attr("src","blank");
document.getElementById("fileAttachment").value = "";
return false;
}
if (file.size > 10485760) {
alert("Individual Image size should not be greater than 10 Mb!");
$("#fileAttachment").attr("src","blank");
document.getElementById("fileAttachment").value = "";
return false;
}
var result = $('div#result');
if (window.FileReader && window.Blob) {
var file = file;
console.log('Loaded file: ' + file.name);
console.log('Blob mime: ' + file.type);
var reader = new FileReader();
reader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0,4);
var header = '';
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log('File header: ' + header);
// Check the file signature against kNown types
var type = 'unkNown';
switch (header) {
case '89504e47':
type = 'image/png';
break;
case 'ffd8ffe0':
case 'ffd8ffe1':
case 'ffd8ffe2':
type = 'image/jpeg';
break;
case '25504446':
type = 'application/pdf';
break;
}
if (file.type !== type) {
alert("File extension doesn't match the image type !");
$("#fileAttachment").attr("src","blank");
document.getElementById("fileAttachment").value = "";
console.log('Mime type detected: ' + type +
'. Does not match file extension.');
} else {
console.log('Mime type detected: ' + type +
'. Matches file extension.');
}
};
reader.readAsArrayBuffer(file);
} else {
result
.html('<span style="color: red; ">Your browser is not supported. Sorry.</span>');
console
.error('FileReader or Blob is not supported by the browser.');
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/yeti/bootstrap.min.css" />
<!DOCTYPE html>
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servlet File Upload/Download</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div style="margin: 50px">
<!-- <h1 style="text-align:center;font-family: garamond,serif ">File Upload</h1> -->
<h2 style="text-align: center; color: black; font-family: courier">
Welcome!
</h2>
<br>
<form id="fileUploadForm" method="post" action="fileUploadServlet" enctype="multipart/form-data">
<div class="form_group">
<div class="form-group">
<label for="staticEmail" class="col-sm-0 col-form-label"><strong>User
Id :</strong></label>
<div class="col-sm-0">
<input type="text" readonly="" class="form-control-plaintext" id="staticId" name="staticId" value="" style="font-family: courier">
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1"><b><strong>Full Name :</strong></b></label> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Full Name" required style="font-family: courier">
</div>
<br>
<div class="form-group">
<label for="exampleTextarea"><b><strong>File
Description :</strong></b></label>
<textarea class="form-control" id="exampleTextarea" rows="3" style="font-family: courier" name="description"></textarea>
</div>
<label><i>Upload File</i></label><span id="colon">: </span><input id="fileAttachment" type="file" name="fileUpload" multiple="multiple" accept="image/jpeg,image/png,.pdf" onchange="restrictTypeAndSize(this)" /> <span id="fileUploadErr"><b><i><strong>Please Choose A File!</strong></i></b></span>
</div>
<button id="uploadBtn" type="submit" class="btn btn-primary" onclick="return showAlert()">Upload</button>
</form>
<br> <br>
<!-- List All Uploaded Files -->
<div class="panel">
<a id="allFiles" class="hyperLink" href="<%=request.getcontextpath()%>/uploadedFilesServlet"><button
type="button" class="btn btn-outline-warning">List all
uploaded files</button></a>
</div>
<div class="panel">
<a id="fileUpload" class="hyperLink" href="<%=request.getcontextpath()%>/index.jsp"><button
type="button" class="btn btn-danger" style="float: right">logout</button></a>
</div>
</div>
</div>
</body>
</html>
解决方法
从您的帖子来看,目前尚不清楚您究竟要完成什么。我了解基础知识。只是不清楚您尝试了什么或希望用户做什么。
我首先清理了一些代码。请考虑以下事项。
$(function() {
function restrictTypeAndSize(o,t,s) {
var r = [];
if (t == undefined) {
t = "image/jpeg";
}
if (s == undefined) {
s = 10485760;
}
$.each(o.files,function(i,f) {
if (t.indexOf(f.type) < 0) {
r.push($.extend({},f,{
error: "Incorrect Type"
}));
} else if (f.size > s) {
r.push($.extend({},{
error: "File Size"
}));
} else {
writeFiles(f);
r.push($.extend({},{
error: false
}));
}
});
return r;
}
function writeFiles(file) {
var result = $('div#result');
if (window.FileReader && window.Blob) {
var file = file;
console.log('Loaded file: ' + file.name);
console.log('Blob mime: ' + file.type);
var reader = new FileReader();
reader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0,4);
var header = '';
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log('File header: ' + header);
// Check the file signature against known types
var type = 'unknown';
switch (header) {
case '89504e47':
type = 'image/png';
break;
case 'ffd8ffe0':
case 'ffd8ffe1':
case 'ffd8ffe2':
type = 'image/jpeg';
break;
case '25504446':
type = 'application/pdf';
break;
}
if (file.type !== type) {
alert("File extension doesn't match the image type !");
$("#fileAttachment").attr("src","blank");
$("#fileAttachment").val("");
console.log('Mime type detected: ' + type +
'. Does not match file extension.');
} else {
console.log('Mime type detected: ' + type +
'. Matches file extension.');
}
};
reader.readAsArrayBuffer(file);
} else {
result
.html('<span style="color: red; ">Your browser is not supported. Sorry.</span>');
console
.error('FileReader or Blob is not supported by the browser.');
}
}
$("#fileAttachment").change(function(e) {
var results = restrictTypeAndSize(this,$(this).attr("accept"));
console.log(results);
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/yeti/bootstrap.min.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<div class="container">
<div style="margin: 50px">
<h2 style="text-align: center; color: black; font-family: courier">Welcome!</h2>
<br>
<form id="fileUploadForm" method="post" action="fileUploadServlet" enctype="multipart/form-data">
<div class="form_group">
<div class="form-group">
<label for="staticEmail" class="col-sm-0 col-form-label"><strong>User Id :</strong></label>
<div class="col-sm-0">
<input type="text" readonly="" class="form-control-plaintext" id="staticId" name="staticId" value="" style="font-family: courier">
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1"><b><strong>Full Name :</strong></b></label> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Full Name" required style="font-family: courier">
</div>
<br>
<div class="form-group">
<label for="exampleTextarea"><b><strong>File Description :</strong></b></label>
<textarea class="form-control" id="exampleTextarea" rows="3" style="font-family: courier" name="description"></textarea>
</div>
<label><i>Upload File</i></label><span id="colon">: </span><input id="fileAttachment" type="file" name="fileUpload" multiple="multiple" accept="image/jpeg,image/png,application/pdf" /> <span id="fileUploadErr"><b><i><strong>Please Choose A File!</strong></i></b></span>
</div>
<button id="uploadBtn" type="submit" class="btn btn-primary" onclick="return showAlert()">Upload</button>
</form>
<br> <br>
<div class="panel">
<a id="allFiles" class="hyperLink" href="<%=request.getContextPath()%>/uploadedFilesServlet"><button type="button" class="btn btn-outline-warning">List all uploaded files</button></a>
</div>
<div class="panel">
<a id="fileUpload" class="hyperLink" href="<%=request.getContextPath()%>/index.jsp"><button type="button" class="btn btn-danger" style="float: right">Logout</button></a>
</div>
</div>
</div>
由于您的文件输入中有 multiple
,因此用户已经可以添加 1 个以上的文件。这一切似乎都有效,但我没有看到所选文件在本地存储的位置,因此用户可以选择更多文件。此时用户应该怎么做?他们怎么知道他们已经选择了哪些文件?如果他们想删除文件怎么办?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。