原生js实现简单的单文件上传操作
效果
核心思想
- 将原生的 <input type="file">隐藏起来,具体来说就是隐藏在【浏览按钮下方】
- 点击浏览按钮时其实点击的是下方的 <input type="file">;
- 将获取到的文件名显示在 <input type="text">的显示栏中
- 使用FormData对象获取文件数据;
- 通过设置ajax的参数,实现数据数据的上传
html代码(具体的业务代码可以忽略)
<div id="scheduleFileUploadDiv"> <div id="scheduleFileChooseDiv"> <input id="scheduleFileNameInput" placeholder="请选择排班文件" type="text" /> <form action="\'+that.scheduleFileUploadUrl+\'" id="scheduleFileUploadForm" enctype="multipart/form-data" style="display: inline-block; "> <input class="scheduleChooseFileInput" id="scheduleFile" type="file" name="file" />浏览 </div> <div class="scheduleFileImportDialogFooterDiv"> <button id="scheduleFileUploadBtn" onclick="scheduleImport.upload()">上传</button> <label id="scheduleImportErrorMsgLabel" style="color: red"></label> </div> </div>
css代码
重点代码加了背景色
#scheduleFileUploadDiv{ width: 700px; height: 110px; } #scheduleFileChooseDiv{ height: 50px; width: 98%; margin: 20px 0px 0px 20px; } .scheduleFileImportDialogFooterDiv { padding: 10px; margin-bottom: 10px; } .scheduleChooseFileInput{ width: 97%; height: 28px; opacity: 0; display: inline-block; position: absolute; top: 0; left: 0; cursor: pointer; } #scheduleFileUploadForm{ position: relative; cursor: pointer; color: #9bcbe6; font-size: 14px; font-weight: 700; line-height: 30px; text-align: center; border: 1px solid #1d5367; border-radius: 2px; /* overflow: hidden; */ width: 100px; background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#254358), to(#0c293c)); margin: 0 7px; } #scheduleFileNameInput{ width: 500px; height: 30px; line-height: 30px; padding: 0 5px; border: 1px solid #9e9a9a; border-radius: 5px; } #scheduleFileUploadBtn{ background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#65b0c7), to(#3d85a0)); border: solid 1px #54a8c0; border-radius: 2px; color: #0c273a; width: 100px; font-size: 14px; font-weight: 700; line-height: 30px; margin-left: 280px; }
js代码
设置文件名显示代码,最好通过setInterval循环设置
refreshUploadFileName:function () { var fileInput = $("#scheduleFile").get(0).files[0]; if(fileInput){ $("#scheduleFileNameInput").val(fileInput.name); } }
文件上传代码
upload:function(){ var that = this; var file = document.getElementById("scheduleFile").files[0]; var formData = new FormData(); formData.append("file",file); $.ajax({ type: 'POST', url: that.scheduleFileUploadUrl, data:formData, cache: false, // 不缓存 processData: false, // jQuery不要去处理发送的数据 contentType: false, // jQuery不要去设置Content-Type请求头 success: function (data){ if(data["success"]){ }else{ } }, error:function(){ }, dataType: "json", async: true }); }
参考文章:
https://segmentfault.com/a/1190000012327982?utm_source=tag-newest
https://www.cnblogs.com/Fancy1486450630/p/10948204.html