文件上传与下载

文件上传与下载


   <button  class="layui-btn layui-btn-sm data-add-btn" lay-event="upload"> 批量上传 </button>
   <button  class="layui-btn layui-btn-sm data-add-btn" lay-event="downTemplate"> 下载模板 </button>
<form id="upload_win" class="layui-form layuimini-form layuimini-hide" lay-filter="edit">
    <div class="layui-upload">
        <button type="button" class="layui-btn layui-btn-normal" id="uploadList">选择多文件</button>
        <div class="layui-upload-list" style="max-width: 1000px;">
            <table class="layui-table">
                <colgroup>
                    <col>
                    <col width="150">
                    <col width="260">
                    <col width="150">
                </colgroup>
                <thead>
                <tr><th>文件名</th>
                    <th>大小</th>
                    <th>上传进度</th>
                    <th>操作</th>
                </tr></thead>
                <tbody id="uploadEl"></tbody>
            </table>
        </div>
        <button type="button" class="layui-btn" id="uploadAction">开始上传</button>
    </div>
</form>
      //演示多文件列表
        var uploadListIns = upload.render({
            elem: '#uploadList'
            ,elemList: $('#uploadEl') //列表元素对象
            ,url: '/smart/ysaq/datasupport/jurisdiction/importExcelData'
            ,accept: 'file' //普通文件
            ,acceptMime: 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            ,exts: 'xlsx|xls' //只允许上传excel文件
            ,multiple: true
            ,number: 3
            ,auto: false
            ,bindAction: '#uploadAction'
            ,choose: function(obj){
                console.info(obj.pushFile())
                var that = this;
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
                    var tr = $(['<tr id="upload-'+ index +'">'
                        ,'<td>'+ file.name +'</td>'
                        ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
                        ,'<td><div class="layui-progress" lay-filter="progress-demo-'+ index +'"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                    });

                    that.elemList.append(tr);
                    element.render('progress'); //渲染新加的进度条组件
                });
            },
            before(obj) {

            }
            ,done: function(res, index, upload){ //成功的回调
                layer.closeAll('loading'); //关闭loading
                if(res.data){
                    layer.msg('上传成功');
                    reload();
                }else {
                    layer.msg("上传失败:"+res.msg)
                }
                var that = this;
                //if(res.code == 0){ //上传成功
                var tr = that.elemList.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(3).html(''); //清空操作
                delete this.files[index]; //删除文件队列已经上传成功的文件
                return;
                //}
                this.error(index, upload);
            }
            ,allDone: function(obj){ //多文件上传完毕后的状态回调
                // layer.msg(JSON.stringify(obj))
            }
            ,error: function(index, upload){ //错误回调
                var that = this;
                var tr = that.elemList.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
            ,progress: function(n, elem, e, index){ //注意:index 参数为 layui 2.6.6 新增
                layer.load(); //上传loading
                element.progress('progress-demo-'+ index, n + '%'); //执行进度条。n 即为返回的进度百分比
            }
        });
        //此方法是解决BUG,可以选择性添加
      end: function (res) {//v2.6.8不会自动隐藏问题
                    $("#edit_win").css("display", 'none');
                }

 
        function downTemplate(){
            var iframe = document.createElement("iframe");
            iframe.style.display = 'none';
            iframe.src = window.location.protocol+ '//' +window.location.host+'/smart/ysaq/datasupport/jurisdiction/downTemplate';
            $('body').append(iframe);
        }

        /**
         * 选择excel
         */
        function openUploadInput(){
            document.getElementById('upload_win').reset();
            openUpload('上传', '800px', '550px');
        }


```java
@Setter
@Getter
public class WaterWorksDto {
    private Integer id;
    //名称
    @ExcelAnnotation(nameCn = "名称")//此注解一定要写
    private String name;

    //水厂工艺
    @ExcelAnnotation(nameCn = "水厂工艺")
    private String technology;

    //面积
    @ExcelAnnotation(nameCn = "面积")
    private Double area;

    //水厂供水量
    @ExcelAnnotation(nameCn = "水厂供水量")
    private BigDecimal dailyWaterSupply;

    //水厂位置
    @ExcelAnnotation(nameCn = "水厂位置")
    private String location;

    //负责人
//    private Integer userId;
//    private String userName;
    @ExcelAnnotation(nameCn = "负责人")
    private  String user;

    //联系电话
    @ExcelAnnotation(nameCn = "联系电话")
    private String contactPhone;

    //经度
    @ExcelAnnotation(nameCn = "经度")
    private String lng;

    //纬度
    @ExcelAnnotation(nameCn = "纬度")
    private String lat;

    //经纬度
    private String lnglat;

    public  WaterWorksDto(){

    }
    public WaterWorksDto(String name,String technology, Double area, BigDecimal dailyWaterSupply,String location ,String user,String contactPhone,String lng,String lat){
        this.name = name;
        this.technology = technology;
        this.area = area;
        this.dailyWaterSupply = dailyWaterSupply;
        this.location = location;
        this.user = user;
        this.contactPhone = contactPhone;
        this.lng = lng;
        this.lat =lat;
    }
//serive层
    public void downTemplate(HttpServletRequest request, HttpServletResponse response) {
        List<WaterWorksDto> examples = new ArrayList<>();
        WaterWorksDto waterWorksDto = new WaterWorksDto(
                "大水泊",
                "大水泊",
                1000d,
                new BigDecimal(100),
                "文登",
                "小李",
                "15678999899",
                "321.2",
                "332.6"


        );
        examples.add(waterWorksDto);
        XSSFWorkbook workbook = ExcelUtils.geneTemplate(WaterWorksDto.class, "水厂管理", examples);
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数,可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = "水厂地管理.xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (IOException e) {
                throw e;
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
                workbook.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void importExcelData(MultipartFile file) throws IOException, BusinessException, InstantiationException, IllegalAccessException {
        InputStream is = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook wb;
        if (fileName.endsWith("xls")) {
            wb = new HSSFWorkbook(is);
        } else if (fileName.endsWith("xlsx")) {
            wb = new XSSFWorkbook(is);
        } else {
            throw new BusinessException("未知格式文件");
        }
        Sheet sheet = wb.getSheetAt(0);
        List<WaterWorksDto> list = ExcelUtils.analysisExcel(WaterWorksDto.class, sheet, true);
        WaterWorks waterWorks;
        for (WaterWorksDto dto : list) {
            waterWorks = dto.toDomain();
            waterWorksRepository.insert(waterWorks);
            }

        }
   //ctrl层
    /**
     * @param : [request, response]
     * @return : void
     * @throws :
     * @Description :下载模板
     * @author : Yuddd
     * @date : 2020/6/9
     */
    @RequestMapping(value = "downTemplate")
    public void downTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        service.downTemplate(request, response);
    }

    /**
     * @param : [file]
     * @return : boolean
     * @throws :
     * @Description :导入
     * @author : Yuddd
     * @date : 2020/6/9
     */

    @RequestMapping(value = "importExcelData", method = RequestMethod.POST)
    public boolean importExcelData(@RequestParam(value = "file") MultipartFile file) throws Exception {
        service.importExcelData(file);
        return true;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值