文件上傳,下載

一、文件上傳:

<div class="layui-form-item">
                <label class="layui-form-label">圖片地址</label>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn" id="imageupload"><i class="layui-icon"></i>上傳圖片</button>
                    <input type="hidden" name="image" id="image" value="">
                </div>
                <label class="layui-form-label">下載地址</label>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn" id="fileupload"><i class="layui-icon"></i>上傳文件</button>
                    <input type="hidden" name="download" id="download" value="">
                </div>
</div>
<!--文件上傳-->
<script>
    layui.use('upload', function(){
        var upload = layui.upload;
        upload.render({   //圖片上傳
            elem: '#imageupload' //綁定元素
            ,url: '/wuxia/book/uploadimages' //上傳接口
            ,done: function(res){
                //上傳完畢回調
                if(res.msg){
                    $('#image').val(res.data);
                    layer.msg("圖片上傳成功",{icon:1});
                }else{
                    layer.msg("圖片上傳失敗",{icon:2});
                }
            }
        });
        upload.render({ //文件上傳
             elem:'#fileupload'
            ,url:"/wuxia/book/uploadbook"
            ,accept:'file'
            ,done:function(res){
                 if(res.msg){
                     $('#download').val(res.data);
                     layer.msg("文件上傳成功",{icon:1})
                 }else{
                     layer.msg("文件上傳失敗",{icon:2})
                 }
            }
        });
    });
</script>

後臺:

 @ApiOperation(value="上傳圖片")
    @PostMapping("/uploadimages")
    public @ResponseBody Map uploadimages(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        boolean msg;
        String savePath = null;
        String image=null;
        try{
            String oldFileName=file.getOriginalFilename();

            String bookimages=UUID.randomUUID().toString().replaceAll("-","");//使用UUID命名防重複
            String prefix=oldFileName.substring(oldFileName.lastIndexOf("."));//得到文件名後綴
            // 1.保存在項目文件裏
            //得到項目名
            String name=request.getServletContext().getContextPath();
            //得到當前文件的物理地址
            String realPath=request.getSession().getServletContext().getRealPath("/");
            //保存文件的地址
            String path = realPath+"files\\images\\bookimages\\"+bookimages;

            savePath=path+prefix;
            System.out.println(realPath);
            File savefile = new File(savePath);
            file.transferTo(savefile);
            //數據庫保存的路徑:
            image = name+"/files/images/bookimages/"+bookimages+prefix;
            msg=true;
        }catch (Exception e){
            msg=false;
        }
        Map<String,Object> map=new HashMap<>();
        map.put("data",image);
        map.put("msg",msg);
        return map;
    }
    @ApiOperation(value="上傳書籍")
    @PostMapping("/uploadbook")
    public @ResponseBody Map uploadbook(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Boolean b = false;
        String path=null;
        try{
           //獲得文件名
           String oldFileName=file.getOriginalFilename();
           //獲取應用的真實根路徑
           String realPath= request.getSession().getServletContext().getRealPath("/");
            //創建帶文件名的真實路徑
//           path = realPath+"files\\books\\"+oldFileName;
            path="D:\\data\\book\\"+oldFileName;
           // 判斷文件是否存在,存在刪除舊文件
            File deleteFile = new File(path);
           if(deleteFile.exists()){
                deleteFile.delete();
           }
           //保存文件
           File savefile=new File(path);
           file.transferTo(savefile);
           b=true;
       }catch(Exception e){
           b=false;
       }
        Map<String,Object> map=new HashMap<>();
        map.put("code", "0");
        map.put("data",path);
        map.put("msg",b);
        return map;
    }

二、文件下載:

  前端:HTML,JS

 可以使用form表單提交,或是window.open(),a標籤跳轉,不能使用ajax提交。

由於是JS動態加載的數據,所以把參數綁定當前列的屬性上了:

<button class="layui-btn layui-btn-small layui-btn-primary download" download="'+list[i].download+'" bookname="'+list[i].bookname+'">下載</button>

 

//下載書籍
        $(document).on("click",".download",function(){
            var bookname=$(this).attr("bookname");
            var download=$(this).attr("download");
            if(ff.isEmpty(download)){
                layer.alert("此資源無法下載");
            }else{
                //第一種:form 表單提交
                var url="/wuxia/book/downloadbook";
                var form = $('<form method="GET" action="' + url + '">');
                form.append($('<input type="hidden" name="download" value="'+download+'">'));
                form.append($('<input type="hidden" name="bookname" value="'+bookname+'">'));
                $('body').append(form);
                form.submit();
            }
        })

  後臺:Java處理

    @ApiOperation(value="下載書籍")
    @GetMapping("/downloadbook")
    public void downloadbook(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(value="download",defaultValue="")String download,
                             @RequestParam(value="bookname")String bookname){
        System.out.println(download+","+bookname);
        File file = new File(download);//得到文件
        String FileName =file.getName();
        response.setCharacterEncoding(request.getCharacterEncoding());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            response.setContentType("application/x-download");//應用程序強制下載
            response.addHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(FileName, "UTF-8"));
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

LayUI 實現文件下載:

<script type="text/html" id="download">
    <a class="layui-btn layui-btn-xs" lay-event="download">下載</a>
</script>
//監聽行內工具欄
        table.on('tool(search)', function(obj){
            var data = obj.data;//獲得當前行數據
            var tr =obj.tr;//獲取當前行tr的DOM對象
           if(obj.event==='download'){
               var url="/wuxia/book/downloadbook";
               var form = $('<form method="GET" action="' + url + '">');
               form.append($('<input type="hidden" name="download" value="'+data.download+'">'));
               form.append($('<input type="hidden" name="bookname" value="'+data.bookname+'">'));
               $('body').append(form);
               layer.confirm('即將下載書籍?', {
                   btn: ['確定','取消'] //按鈕
               }, function(){
                   form.submit();
                   layer.msg('正在下載', {icon: 1});
               }, function(){
                   layer.msg('好的');
               });
           }
       }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章