上传下载,克服浏览器文件路径保密(本例子为导入excel表)

来源:互联网 发布:淘宝cpu 编辑:程序博客网 时间:2024/05/20 07:53

js前台导入代码

$(".btn-import")
                .click(
                        function() {
                            layer.open( {
                                title : "选择文件",
                                type : 1,
                                area : [ '300px', '250px' ], //宽高
                                skin : 'layui-layer-molv', //样式类名
                                closeBtn : 2, //显示关闭按钮
                                shift : 2,
                                shadeClose : true, //开启遮罩关闭
                                content : $(".btn-import")
                .click(
                        function() {
                            layer.open( {
                                title : "选择文件",
                                type : 1,
                                area : [ '300px', '250px' ], //宽高
                                skin : 'layui-layer-molv', //样式类名
                                closeBtn : 2, //显示关闭按钮
                                shift : 2,
                                shadeClose : true, //开启遮罩关闭
                                content : uploadHTML
                            });
                            $(".file1").click( function() {
                                $(".file").click();
                            });
                            $("#uploadFile")
                                    .change(
                                            function() {
                                                var path = $("#viewfile").val(
                                                        $(".file").val());
                                                if (!isExcel(path)) {
                                                    UI.util
                                                            .alert(
                                                                    "上传的文件格式不正确,请选择97-2003Excel文件(*.xls)!",
                                                                    "message");
                                                    return;
                                                }
                                            });
                            $("#submitBtn").click( function() {
                                var ii = layer.load();
                            });
                        });
                            });
                            $(".file1").click( function() {
                                $(".file").click();
                            });
                            $("#uploadFile")
                                    .change(
                                            function() {
                                                var path = $("#viewfile").val(
                                                        $(".file").val());
                                                if (!isExcel(path)) {
                                                    UI.util
                                                            .alert(
                                                                    "上传的文件格式不正确,请选择97-2003Excel文件(*.xls)!",
                                                                    "message");
                                                    return;
                                                }
                                            });
                            $("#submitBtn").click( function() {
                                var ii = layer.load();
                            });
                        });

uploadHTML是这样的:

var uploadHTML = '<div class="upload-box">'
        + '<div><span style="font-size:11px;color:red;">1、请按照模板样式要求添加数据后再导入(主页面下载模板)</div>'
        + '<div><span style="font-size:11px;color:red;">2、详细导入过程信息请导入后查看导入日志(导入日志存放在d盘的importLog文件夹)</div>'
        + '<form class="upload-form" enctype="multipart/form-data" action="doUpload.jsp" method="post">'
        + '<div class="upload-up" >'
        + '<input name="" type="text" id="viewfile"  class="inputstyle" />'
        + '<label for="unload" class="file1" >浏览...</label>'
        + '<input type="file" class="file" display="none"name="uploadFile" id="uploadFile" />'
        + '<input type="submit" class="myButton" name="submitBtn" id="submitBtn" value="导入"/>'
        + '</div>' + '</div>'

然后跳到jsp运行java

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="com.suntek.monstuff.web.*"%>
<%@ page import="com.suntek.monstuff.provider.DeviceInfoProvider"%>



<%@ page import="java.io.File"%>
<%@ page import="java.io.IOException"%>
<%@ page import="java.io.InputStream"%>
<%@ page import="java.io.RandomAccessFile"%>
<%@ page import="java.io.FileNotFoundException"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>

<%@ page import="javax.servlet.ServletException"%>
<%@ page import="javax.servlet.http.*"%>

<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="com.suntek.monstuff.common.util.DateUtil"%>




<html>
<head>
<title>upFile</title>
</head>

<body bgcolor="#ffffff">
<%
String logPath="";
String content="";
    try {
        // 创建'DiskFileItemFactory'对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        // 创建'ServletFileUpload'对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(
                diskFileItemFactory);

        //String jobreportId = "";
        //String jobreportType = "";
        String message = "";

        // 获取Http请求消息 ('Request') 中的所有请求参数 (包括普通参数以及上传的内容)
        List<FileItem>   fileItems = servletFileUpload
                .parseRequest(request);
        FileItem s = fileItems.get(0);
        System.out.println("fileItems.get(0)=" + s);

        // 循环取出Http请求消息 ('Request') 中的所有请求参数
        for (FileItem fileItem : fileItems) {
            // 如果该Http请求消息中的参数是普通参数 (表单中的一个普通值)
            if (fileItem.isFormField()) {
                // 获得表单中的普通参数值 (上传者, 文件的等级), 使用UTF-8的编码格式获取该普通参数的值
                String requestOfValue = fileItem.getString("UTF-8");
                // 获得表单中的普通参数在请求中所对应的名字
                String requestForName = fileItem.getFieldName();

                //    if("jobreportId".equals(requestForName)){
                //    jobreportId = requestOfValue;
                //}
                //if("jobreportType".equals(requestForName)){
                //    jobreportType = requestOfValue;
                //}

                System.out.println("表单中的普通参数: (" + requestOfValue
                        + "), 表单中的名字为'" + requestForName + "'");
                // 如果该Http请求消息中的参数是上传的内容
            } else {
                // 获得上传文件的名字 (文件上传框中, 上传文件的名字, 注意: 该名字已被截取, 并不是文件的完整路径)
                String fileName = fileItem.getName();
                System.out.println("fileName=" + fileName);

                // 用户选择了上传的文件, 并且该文件的名字不为空
                if (fileItem.getName() != null
                        && !"".equals(fileItem.getName())) {
                    // 获得上传文件的类型
                    String contentType = fileItem.getContentType();
                    System.out.println("contentType=[" + contentType
                            + "]");
                    // 获得上传文件的大小
                    long fileSize = fileItem.getSize();
                    String fileSaveName = fileItem.getName();
                    String realPath = this.getClass().getResource("/")//获取项目的绝对路径,是项目在服务器运行的路径
                            .getPath();
                    realPath = realPath.substring(1, realPath
                            .indexOf("monstuff/"))
                            + "monstuff/META-INF/uploadFiles/";
                    System.out.println("realPath=" + realPath);
                    String date = DateUtil.getCurrentDateTimeForID();
                    System.out.println("is fileSaveName contains /?"
                            + fileSaveName.contains("/"));
                    System.out.println("is fileSaveName contains \\?"
                            + fileSaveName.contains("\\"));

                    System.out.println("before process...filename=["
                            + fileSaveName + "]");
                    if (fileSaveName.contains("\\/")) {
                        fileSaveName = fileSaveName.substring(
                                fileSaveName.lastIndexOf("\\/"),
                                fileSaveName.length());
                    }
                    if (fileSaveName.contains("\\")) {
                        fileSaveName = fileSaveName.substring(
                                fileSaveName.lastIndexOf("\\"),
                                fileSaveName.length());
                    }

                    System.out.println("after process...filename=["
                            + fileSaveName + "]");
                    String fileType = fileSaveName.substring(
                            fileSaveName.indexOf("."), fileSaveName
                                    .length());
                    if (!fileSaveName.endsWith(".xls")) {
                        message = "导入的文件格式不正确,请选择97-2003Excel文件(*.xls)!";
                        request.setAttribute("uploadTips", message);

                    } else {
                        //    fileSaveName = jobreportId + fileType;
                        System.out.println("fileSaveName="
                                + fileSaveName);
                        // 打印Http请求消息 ('Request') 中上传文件的信息
                        //                System.out.println("上传的文件名: " + fileName);
                        //                System.out.println("上传的文件类型: " + contentType);
                        //                System.out.println("上传的文件大小: " + fileSize);
                        //String fileSaveDirPath = Constants.JOBREPORT_FILE_PATH + "\\" + "deviceInfo" + "\\" + jobreportId + "\\";
                        //System.out.println("fileSaveDirPath="+fileSaveDirPath);
                        //File saveFileUploadFile = new File(fileSaveDirPath);
                        realPath = realPath + "deviceInfo" + "/";
                        File saveExcelFile = new File(realPath);
                        String ExcelName = date + fileType;
                        // 如果保存上传文件的目录不存在, 创建
                        if (!saveExcelFile.exists()) {
                            saveExcelFile.mkdirs();
                        }
                        //File saveTheFileUpload = new File(fileSaveDirPath, fileSaveName);
                        File ExcelUpload = new File(realPath, ExcelName);

                        // 保存上传的文件
                        //    fileItem.write(saveTheFileUpload);
                        fileItem.write(ExcelUpload);//在这里上传文件上传到服务器,服务器文件路径是上方编程人员拼出来的,然后把服务器的路径交个java后,进行处理本例是导入excel表数据,自然是处理excel中的数据

                        System.out.println("realPath=" + realPath);
                        System.out.println("ExcelName=" + ExcelName);

                        //String jobreportFile = saveTheFileUpload.getAbsolutePath();
                        String path = ExcelUpload.getAbsolutePath();
                    
                        //    long size = saveTheFileUpload.length();
                        //jobreportFile.replaceAll("\\","/");
                        DeviceInfoProvider Into = new DeviceInfoProvider();
                        try {
                            Map<String, Object> result = Into.importData(path);
                            String state = result.get("state").toString();
                            message = result.get("message").toString();
                            logPath=result.get("path").toString();
                            content=result.get("content").toString();
                            content=content.replace("再导入","再导入\r\n");
                            content=content.replace("导入日志*********","导入日志*********\r\n");
                            if (state.equals("1")) {
                                request.setAttribute("state", "1");
                                request.setAttribute("uploadTips",
                                        "导入结束:"+message+"(详细请查看导入日志)");

                            } else {
                                File logFile = new File(logPath);
                                if (!logFile.exists()) {
                                    logFile.createNewFile();
                                }
                                OutputStreamWriter write  = new OutputStreamWriter(new FileOutputStream(logFile),"gbk");      
                                BufferedWriter mm=new BufferedWriter(write);
                                content=content+"\r\n";
                                request.setAttribute("uploadTips",
                                        "导入结束:" + message+"(详细请查看导入日志)");
                                mm.write(content+message+ "\r\n");
                                mm.close();
                            }
                        } catch (Exception e) {
                            File logFile = new File(logPath);
                            if (!logFile.exists()) {
                                logFile.createNewFile();
                            }
                            OutputStreamWriter write  = new OutputStreamWriter(new FileOutputStream(logFile),"gbk");      
                            BufferedWriter mm=new BufferedWriter(write);
                            e.printStackTrace();
                            content=content+"\r\n";
                            request.setAttribute("uploadTips", "后台错误:"
                                    + e.toString()+"(详细请查看导入日志)");
                            mm.write(content+e.toString()+ "\r\n");
                            mm.close();
                        }//
                    }

                }else{
                     request.setAttribute("uploadTips", "请选择文件后再导入!");
                     break;
                }
            }
        }

    } catch (Exception e) {
        File logFile = new File(logPath);
        if (!logFile.exists()) {
            logFile.createNewFile();
        }         
        OutputStreamWriter write  = new OutputStreamWriter(new FileOutputStream(logFile),"gbk");      
        BufferedWriter mm=new BufferedWriter(write);
        request.setAttribute("uploadTips", "操作失败!"+"(详细请查看导入日志)");
        e.printStackTrace();
        content=content+"\r\n";
         mm.write(content+e.toString()+ "\r\n"); mm.close();
%>

<div>操作失败!</div>
<%
        }
    %>
</body>
<script type="text/javascript" src="/ui/plugins/jquery.min.js"></script>
<script type="text/javascript" src="/monstuff/js/layer/layer.js"></script>
<script type="text/javascript" src="/ui/plugins/eapui/eapui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    
    var tips = "<%=request.getAttribute("uploadTips")%>";
    var state = "<%=request.getAttribute("state")%>"
    if(state == "1"){
        UI.util.alert(tips);
    }else{
        UI.util.alert(tips, "warn");
    }
    parent.showForm("/monstuff/page/assetManage/deviceInfo/deviceInfo.html");
});

</script>
</html>

在这个jsp文件路径以保密的方式传到后台

接下来是下载它(没有路径保密的问题)

js前台是这样的,跳到jsp页面

    // 导入模板下载
    if (UI.control.hasPermission("menu_btn_device_downfile")) {
        $("body")
                .on(
                        'click',
                        ".btn-download",
                        function() {
                            window.location.href = '/monstuff/page/assetManage/deviceInfo/doDownload.jsp';
                        });
    } else {
        $(".btn-download").attr("disabled", "disabled");
    }

jsp里的内容是这样的


<%@page language="java" contentType="application/x-download;charset=UTF-8"%>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="java.io.*" %>


<%
    //关于文件下载时采用文件流输出的方式处理:
    //加上response.reset(),并且所有的后面不要换行,包括最后一个;
    
    response.reset();
    response.setContentType("application/x-download");
    String path = this.getClass().getClassLoader().getResource("/").getPath();
    //String r = System.getProperty("user.dir");
    path=path.substring(1,path.length()-16)+"META-INF/Templete/设备信息导入模板.xls";
    System.out.println("path=["+path+"]");
    String excelName="importTemp.xls";
    excelName = URLEncoder.encode(excelName,"UTF-8");
    response.addHeader("Content-Disposition","attachment;filename="+excelName);
    response.addHeader("Cache-Control", "no-transform, max-age=0");
    java.io.OutputStream outp = null;
    java.io.FileInputStream in =null;
    //String filenameDownload = filedownload;
//    System.out.println("filenameDownload=["+filenameDownload+"]");
    try{
        outp = response.getOutputStream();
        in = new FileInputStream(path);
        
        byte[] b = new byte[1024];
        int i = 0;
        while((i = in.read(b))>0){
            outp.write(b, 0, i);
        }
        outp.flush();
        
        out.clear();
        out = pageContext.pushBody();
        
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(in != null){
            in.close();
            in = null;
        }
        if(outp != null){
            outp.close();
            outp = null;
            response.sendRedirect("/monstuff/page/assetManage/deviceInfo/deviceInfo.html");
        }
        
    }
%>
效果上传(火狐浏览器)

效果下载



0 0
原创粉丝点击