jQuery File Upload 上传组件的使用

曹自怡
2023-12-01

客户端

<form id="fileupload" action="${ctx}/general/uploadgeneralfile" method="POST" enctype="multipart/form-data">
        <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
                <span class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <span>上传文档</span>
                    <input type="file" name="files[]" multiple>
                </span>
                <span class="fileupload-process"></span>
            </div>
            <div class="col-lg-5 fileupload-progress fade">
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                </div>
                <div class="progress-extended">&nbsp;</div>
            </div>
        </div>
        <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    </form>

 

<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            <strong class="error text-danger"></strong>
        </td>
        <td>
            <p class="size">Processing...</p>
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
        </td>
        <td>
            {% if (!i && !o.options.autoUpload) { %}
                <button class="btn btn-primary start" disabled>
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>上传</span>
                </button>
            {% } %}
            {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>取消</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
 {% if (file.name) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview">
                {% if (file.thumbnailUrl) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                    <span>{%=file.name%}</span>
                {% } %}
            </p>
        </td>
        <td>
            <span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td>
            {% if (file.deleteUrl) { %}
                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>删除</span>
                </button>
                <input type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>取消</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
{% } %}
</script>

 

$(function () {
    $('#fileupload').fileupload({
           success:function(data){    
           var str="<tr><td >上传成功<span><input type=\"hidden\" value=\""+data.attachFilePath+"\" name=\"filepath\"><input type=\"hidden\" value=\""+data.objctType+"\" name=\"objctType\"><input type=\"hidden\" value=\""+data.attachFileName+"\" name=\"filename\"></span></td>";
           str+="<td >"+data.fileName+"</td><td >"+data.size+"</td>";
           str+="<td><button class=\"btn btn-danger delete\" οnclick=\"deletefile(this)\"><i class=\"glyphicon glyphicon-trash\"></i> <span>删除</span></button></td></tr>"
           $('#successfile').append(str);
           }
    });
    
    $('#imageupload').fileupload({
           success:function(data){    
           var str="<tr><td >上传成功<span><input type=\"hidden\" value=\""+data.attachFilePath+"\" name=\"filepath\"><input type=\"hidden\" value=\""+data.objctType+"\" name=\"objctType\"><input type=\"hidden\" value=\""+data.attachFileName+"\" name=\"filename\"></span></td>";
           str+="<td >"+data.fileName+"</td><td >"+data.size+"</td>";
           str+="<td><button class=\"btn btn-danger delete\" οnclick=\"deletefile(this)\"><i class=\"glyphicon glyphicon-trash\"></i> <span>删除</span></button></td></tr>"
           $('#successfile').append(str);
           }
    });

})

 

function saveorggeneral(){
    //换届基本信息
    var orgId =$("#orgId").val();
    var number =$("#number").val();
    var tenure = $("#tenure").val();
    var time = $("#time").val();
    var style = $("#style").val();
    var shouldnum = $("#shouldnum").val();
    var actualnum = $("#actualnum").val();
    var remark = $("#remark").val();
    var str='';
    str += '{"orgId":"' + orgId
                + '","number":"' + number
                + '","tenure":"' + tenure
                + '","time":"' + time
                + '","style":"' + style
                + '","shouldnum":"' + shouldnum
                + '","actualnum":"' + actualnum
                + '","remark":"' + remark
                + '","attach":';
//附件信息
var attachstr='[';
//循环长度
var len =$ ("#successfile tr").length;
$('#successfile tr').each(function(i, dom){
  var attachFileName=$(this).find("input[name='filename']").val();
  var attachFilePath=$(this).find("input[name='filepath']").val();
  var objctType=$(this).find("input[name='objctType']").val();
  attachstr += '{"attachFileName":"' + attachFileName
                + '","objctType":"' + objctType
                + '","attachFilePath":"' + attachFilePath+'"}';
            if (i < len - 1)
            {
            attachstr+=",";     
            }
});
attachstr+="]";    
str+=attachstr+'}';    
        $.ajax({    
        url:'${ctx}/general/addpartygeneral',     
        type:'post',
        cache:false,
        data:{
      str : str,
        },
        error:function(){
           layer.msg('请按照提示正确填写!');      
        },     
        success:function(){    
        var url="${ctx}/general/listplus?orgid="+orgId;
        window.parent.loaddiv(url);
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);
        }
    });
    }
//删除文件
function deletefile(obj){
var filename=$(obj).parents('tr').find("input[name='filename']").val();
var filepath=$(obj).parents('tr').find("input[name='filepath']").val();
var path =filepath+"\\"+filename;
//ajax删除服务器文件
$.ajax({    
        url:'${ctx}/file/deletefile',     
        type:'post',
        cache:false,
        data:{
      path : path,
        },
    });
//移除tr
$(obj).parents('tr').remove();
}

------------------------------------------------------------------------------------------------------------------------------------------------------

服务器端

//上传换届附件
        @RequestMapping(value = "/uploadgeneralfile", method = RequestMethod.POST)
        @ResponseBody
        public PartyGeneralManagementAttach uploadgeneralfile(HttpServletRequest request
                ,@RequestParam(value = "orgid", required = false) Integer orgid)
                throws IllegalStateException, IOException {
             //换届附件信息
            PartyGeneralManagementAttach attach = uploadgeneral(request);
            attach.setObjctType(1);
            return attach;
        }

 

private PartyGeneralManagementAttach uploadgeneral(HttpServletRequest request )
                throws IOException {
            PartyGeneralManagementAttach attach =new PartyGeneralManagementAttach();
            // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                // 将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                String newFileName = "";
                // 设置保存路径为tomcat下的...
                ServletContext context = request.getSession().getServletContext();
                String relativePath = "/upload/";
                String savePath = context.getRealPath(relativePath);
                File f = new File(savePath);
                // 创建文件夹
                if (!f.exists()) {
                f.mkdirs();
                }
                while (iter.hasNext()) {
                    // 一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next()
                            .toString());
                    if (file != null) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        // 新文件名为原名+日期+随机数
                        newFileName =  df.format(new Date()) + "_"
                                + new Random().nextInt(1000) + "." + file.getOriginalFilename();
                        // 上传
                        file.transferTo(new File(savePath, newFileName));
                        
                        attach.setAttachFileName(newFileName);
                        attach.setAttachFilePath(relativePath);//相对路径
                        attach.setFileName(file.getOriginalFilename());
                        //转换文件大小
                        String size = "0BT";
                        long fileS = file.getSize();
                          DecimalFormat dft = new DecimalFormat("#.00");
                               if (fileS < 1024) {
                                   size = dft.format((double) fileS) + "BT";
                               } else if (fileS < 1048576) {
                                   size = dft.format((double) fileS / 1024) + "KB";
                               } else if (fileS < 1073741824) {
                                   size = dft.format((double) fileS / 1048576) + "MB";
                               } else{
                                   size = dft.format((double) fileS / 1073741824) +"GB";
                               }
                               attach.setSize(size);
                    }
                }
            }
            return attach;
        }

 

 

/**
           * 根据组织id得到文件路径
           * title
           * 创建人:cjq  
           * 创建时间:2017年6月1日 下午4:27:34   
           * @param @param orgid
           * @param @return   
           * @return String
           */
          public static String getfilepath(Integer orgid,PartyInfoService partyinfoservice,String relativePath)
        {
              
              PartyOrganization org=partyinfoservice.selectOrgByid(orgid);
              if(org!=null){
                  relativePath="/"+org.getOrgName()+relativePath;
                  if(!org.getId().equals(org.getParentid())){
                      relativePath =    getfilepath(org.getParentid(),partyinfoservice,relativePath);   //递归调用返回值时记得接收
                  }
              }
              return relativePath;
        }

转载于:https://www.cnblogs.com/1234cjq/p/6929375.html

 类似资料: