0

常用的上传和下载

 2 years ago
source link: https://segmentfault.com/a/1190000041076548
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

常用的上传和下载

发布于 12 月 7 日

使用Jquery的框架

    1. 使用a标签 download属性

      <a id="down" href="url" download="文件名">点击下载</a>
    2. 使用button加window.location.href

      <a class="nui-button" onclick="exportFile">点击下载</a>
      
      <script>
      function exportFile(){
          var url = "";
          window.loaction.href=url;
      }
      </script>
    3. 后端下载目前返回的是ResponseEntity<byte[]>类型,尽量避免报错,否则前端需要另写函数捕捉报错信息,如果没有查到相关信息则返回空。
    1. 使用input的file属性
    <a class="file">
     选择文件:<input type="file" id="upload"/>
    </a>
    
    <script>
    //可以通过click事件,在上传之前加限制条件
     $("#upload").click(function(){
    
         if(){
             return false;//不会再进入文件选择
         }else{
             $("#upload").change(
         function(e){
             //取到文件
             var fileName=e.target.name;
             var fileId=e.target.id;
             var file=$("#"+fileId)[0].files;
             //判断文件是否满足条件
             var max_size=1024*1024*1;
             //一般上传文件用FormData存储键值对的格式模拟表单提交
             var fileData=new FormData();
             if(file.length==0||file[0].size>=max_size){
                 alert("未上传文件或者,文件过大。");
    return;
    
             }
             var uploadUrl="";
             //用ajax上传文件流
             $.ajax({
                 url: uploadUrl,
                 type: "POST",
                 data: fileData,
                 contentType: false,
                 success: function(res){
                     //处理上传返回结果
                 }
                 
             })
         }
     )
         }
     })
     
    </script>
    //通过外包a标签重定义文件上传的样式,主要通过将input的opacity设置为0,隐藏了。
    <style>
     .file{
         position: relative;
         display: inline-block;
         background: #D0EEFF;
         border: 1px solid #99D3F5;
         border-radius: 4px;
         padding: 4px 12px;
         overflow: hidden;
         color: #1E88C7;
         text-decoration: none;
         text-indent: 0;
         line-height: 24px;//根据Input外的高度
     }
       .file input{
         position: absolute;
         font-size: 100px;
         right: 0;
         top: 0;
         opacity: 0;
     }
    </style>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK