欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

bootstrap+SpringMVC 实现多文件上传

程序员文章站 2022-05-30 20:35:41
...

        前端时间公司需要附件可以一次选择多个文件上传,网上找了很多资料,前前后后找资源都很难搞定,最开始搜到的是swf来上传,但是那个flash插件用起来蛮不好用,博主果断抛弃这种做法,即便是前台界面配合extjs还不错的情况下。其次,用到的ajax实现多文件上传,做完之后,界面实在太丑,又果断弃之。最后,功夫不负有心人,我找到bootstrap+file input自带的俩文件,直接搞定,而且前台界面也很酷炫。

资源打包:全部代码,点击下载

先来看看前台界面的效果吧.

bootstrap+SpringMVC 实现多文件上传

bootstrap+SpringMVC 实现多文件上传

我们移除掉不符合的文件,截图如下:

bootstrap+SpringMVC 实现多文件上传

        这时候相应的文件会显示正常,准备上传的状态,当然,细心的朋友会发现,这些文件均有一个可在线预览的效果,点开搜索图标,放大预览效果,如下图:

bootstrap+SpringMVC 实现多文件上传

上图中的滚动条可拉伸,预览整个文件的,当然文件可以选择单个点击上传也可以点击上传按钮一次全部上传,这里就全部上传了,看下图效果:

bootstrap+SpringMVC 实现多文件上传

上传均显示100%,则表示已经上传完毕。我们关闭上传弹窗,去列表看看我们刚才上传的数据:

bootstrap+SpringMVC 实现多文件上传

好了,具体的功能等小伙伴实现了在自己去体验吧,比如拖拽啊等效果等等。下面直接上代码吧。

前台代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<%@page import="com.sunwayworld.icore.cache.ApplicationCache"%>
<%@page import="com.sunwayworld.iframework.utils.StringUtils"%>
<%
    //附带的额外参数
    String businesscode = StringUtils.toString(request.getParameter("businesscode"));
    String businessobjectid = StringUtils.toString(request.getParameter("businessobjectid"));
    String handletype = StringUtils.toString(request.getParameter("handletype"));
    String version = StringUtils.toString(request.getParameter("version"));
    //弹窗ID处理,用于窗口关闭
    String win_id = StringUtils.toString(request.getParameter("winid"));
%>
<!DOCTYPE html>    
<html>    
<head>    
<title>文件批量上传</title>    
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="css/bootstrap.min.css">    
<link rel="stylesheet" href="css/fileinput.min.css" />  
<script src="js/jquery-3.2.1.min.js"></script>    

<script type="text/javascript" src="js/fileinput.min.js"></script>  
<script type="text/javascript" src="js/zh.js"></script>
<script type="text/javascript" src="js/fileinput_locale_zh.js"></script>   
<script src="js/bootstrap.min.js"></script>  
 
</head>  
<body>  
<div class="container-fluid">  
    <form id="form" action="" method="post" enctype="multipart/form-data">  
      <div >  
         <div class="panel panel-primary">  
           <div align="right" >  
             <!--添加手动关闭,根据决堤项目设计的,也可以不要-->
             <button class="btn btn-default" id="colseid" type="button" tabindex="500" style="text-align: center;font-size: 15px;" >关闭</<button>
           </div>  
         <div class="panel-body" style="padding-top: 0px;padding-top: 0px;padding-right: 0px;">  
           <div >  
              <input id="input-id" name="file" multiple type="file" data-show-caption="true">  
           </div>  
         </div>  
        </div>  
      </div>  
    </form>  
</div>  
 <script type="text/javascript">  
        $(function () {  
            initFileInput("input-id");  
            var win_id = '<%=win_id%>';
            $("#colseid").click(function() {
                if(win_id){
                    parent.Ext.getCmp(win_id).close();
                }
            });
        })  
                 
        function initFileInput(ctrlName) {  
            var control = $('#' + ctrlName);
            var businesscode = '<%=businesscode%>';
            var businessobjectid = '<%=businessobjectid%>';
            var handletype = '<%=handletype%>';
            var version = '<%=version%>';
            var SRM_CONTEXT = '<%=request.getContextPath()%>';
            //var extraParams = {"businesscode":businesscode,"businessobjectid":businessobjectid,"handletype":handletype,"version":version};
            var url = SRM_CONTEXT + "/icore/upload/uploadBatch?businesscode="+businesscode+"&businessobjectid="+businessobjectid+"&handletype="+handletype+"&version="+version;
            var version = '<%=version%>';  control.fileinput({  
                language: 'zh', //设置语言  
                uploadUrl: url,  
                allowedFileExtensions: ['tif','jpg','png','gif','bmp','txt','html','xml','pdf','doc','xls','ppt','docx','xlsx','pptx','zip','rar','mp3','mov','avi','mpp'],//接收的文件后缀  
                maxFilesNum : 5,//上传最大的文件数量  
                //uploadExtraData:function(previewId, index) { return extraParams; },
                uploadAsync: true, //默认异步上传  
                showUpload: true, //是否显示上传按钮  
                showRemove : true, //显示移除按钮  
                showPreview : true, //是否显示预览  
                showCaption: false,//是否显示标题  
                browseClass: "btn btn-primary", //按钮样式  
                dropZoneEnabled: true,//是否显示拖拽区域  
                //minImageWidth: 50, //图片的最小宽度  
                //minImageHeight: 50,//图片的最小高度  
                //maxImageWidth: 300,//图片的最大宽度  
                //maxImageHeight: 200,//图片的最大高度  
                maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小  
                //minFileCount: 0,  
                //maxFileCount: 10, //表示允许同时上传的最大文件个数  
                enctype: 'multipart/form-data',  
                validateInitialCount:true,  
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",  
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",  
 
            }).on('filepreupload', function(event, data, previewId, index) {     //上传中  
                var form = data.form, files = data.files, extra = data.extra,  
                response = data.response, reader = data.reader;  
                console.log('文件正在上传');  
            }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功  
                console.log('文件上传成功!'+data.id);  
 
            }).on('fileerror', function(event, data, msg) {  //一个文件上传失败  
                console.log('文件上传失败!'+data.id);  
            })  
            }  
 </script>  
</body>  
</html> 

后台代码:

package com.sunwayworld.icore.upload.controller;

import com.alibaba.fastjson.JSON;
import com.sunwayworld.icore.upload.service.UploadService;
import com.sunwayworld.icore.upload.valueobject.UploadFileInfo;
import com.sunwayworld.iframework.bean.FileBean;
import com.sunwayworld.iframework.bean.SplitPage;
import com.sunwayworld.iframework.bean.VCommList;
import com.sunwayworld.iframework.controller.FileController;
import com.sunwayworld.iframework.controller.IUploadReceiver;
import com.sunwayworld.iframework.exception.RunException;
import com.sunwayworld.iframework.upload.FileManager;
import com.sunwayworld.iframework.utils.BeanUtils;
import com.sunwayworld.iframework.utils.FileUtils;
import com.sunwayworld.iframework.utils.MD5Util;
import com.sunwayworld.iframework.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 附件上传下载处理类
 */
@Controller
@RequestMapping("/icore/upload")
public class UploadController extends FileController {

    @Resource
    private UploadService uploadService;
    
    /*
     * 上传多个文件,后台代码主要是接收参数,其他的业务代码根据你们具体的业务需求来定
     */
    @RequestMapping(value = "/uploadBatch", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody Map<String, Object> uploadBatch(HttpServletRequest request,@RequestParam("file") MultipartFile [] files,String businesscode,String businessobjectid,String handletype,Long version) {
    	final String fileDirServerSide = getWorkdir();
    	final List<UploadFileInfo> files_re = new ArrayList<UploadFileInfo>();
        String workPath = FileManager.getRealPath(StringUtils.isNotEmpty(fileDirServerSide) ? fileDirServerSide : FileController.getWorkdir());
    	try {
			for(int i=0;i<files.length;i++){
			    if (!files[i].isEmpty()) { 
			    	String originalname = files[i].getOriginalFilename();
			    	if(StringUtils.isEmpty(originalname)) { continue; }
			    	String uuid = UUID.randomUUID().toString();
			    	String contentType = files[i].getContentType();
			        String suffixname = originalname.substring(originalname.lastIndexOf("."));
			    	UploadFileInfo uploadFile = new UploadFileInfo();
			        uploadFile.setFilename(originalname);
			        uploadFile.setFiletype(contentType);
			        FileBean fbean = new FileBean();
			        String filename = workPath + uuid + suffixname;
			        String uuid_ = uuid + suffixname;
                    fbean.setOriginalname(originalname);
                    fbean.setFilename(filename);
                    fbean.setUuid(uuid_);
                    fbean.setContenttype(contentType);
                    File tfile = fbean.getFile();
                    files[i].transferTo(tfile); // 存储服务器临时文件,设置定时任务清理30天前的
                    String md5code = MD5Util.getFileMD5String(tfile);
			        uploadFile.setMd5code(md5code);
			        uploadFile.setFilenameserverside(uuid_);
			        uploadFile.setFiledirserverside(fileDirServerSide);
			        uploadFile.setFilesize(files[i].getSize() + "");
			        uploadFile.setBusinesscode(businesscode);
			        uploadFile.setBusinessobjectid(businessobjectid);
			        uploadFile.setHandletype(handletype);
			        uploadFile.setVersion(version);
			        uploadFile.setRecordercode(getCurrentUser().getUsercode());
			        uploadFile.setRecorderdesc(getCurrentUser().getUserdesc());
			        uploadFile.setRecordtime(new Date());
			        uploadService.insertUploadFile(uploadFile);  
			        files_re.add(uploadFile);
			    }
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    	String json = toJSON(files_re);
        return uploadReturn(true, json);
    }
    

}

当然,前台需要导的包啊很多地方都有下载,下载会后样式啊均可以修改,博主之前前台传参的时候用uploadExtraData属性传参没啥效果,后面就直接用url以get方式传参数,后续博友们可以尝试一下,看是否可以实现这种方式的传参,本来想把代码打包贡献出来的,但是没找着,望广大博友们见谅!