GWT - Java - 我试图将文件的路径从客户端传递到服务器端

GWT - Java - I am trying to pass the path of a file from client side to server side

我正在尝试将文件路径从客户端传递到服务器端,但我正在获取我当前的工作目录。客户端代码是:

// Create a FileUpload widget.
final FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
horizontalDatesPanel.add(upload);

//Add an Export button
Button btnExport = new Button("Export Details");
btnExport.setWidth("105px");
btnExport.addClickHandler(new ClickHandler() {
    public void onClick(ClickEvent event) {
        String filePath = upload.getFilename();

        if (filePath.length() == 0) {
            Window.alert("No File Specified!");
        } else {
            List<String> printLine = Arrays.asList("1st line", "2nd line");

            AsyncCallback<Void> callback = new PrintSummaryHandler<Void>(PackSummaryView.this);
            rpc.printToFile(filePath, printLine, callback);                   
        }


    }
});
horizontalDatesPanel.add(btnExport);

服务器端代码是:

public void printToFile(String filePath, List<String> printLine) {

    Charset utf8 = StandardCharsets.UTF_8;
    List<String> lines = Arrays.asList("1st line", "2nd line");

    if (filePath != null) {
        filePath = FilenameUtils.getName(filePath);
        filePath = getServletContext().getRealPath(filePath);
        System.out.println("File path = " + filePath);

        try {
            Files.write(Paths.get(filePath), lines, utf8);
            //Files.write(Paths.get("C:\Users\Glyndwr\Documents\file5-test.txt"), lines, utf8);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Done
}

我select的文件是C:\Users\Glyndwr\Documents\file5-test.txt 打印的文件路径和创建位置是 C:\Tomcat\webapps\awardtracker_n\file5-test.txt

不正是你想要的吗?

FilenameUtils.getName 丢弃仅保留文件名的路径 (file5-test.txt),然后 ServletContext#getRealPath 将为您提供该文件的绝对路径,如果它是相对于webapp 的上下文路径)

顺便说一句,作为一项安全措施,您永远不会在现代浏览器中获得真实的文件路径,它始终是 C:\fakepath\: http://www.w3.org/TR/html5/forms.html#dom-input-value-filename

这个问题的答案是由一位同事提供的,是采取不同的方法。在服务器端获取信息,return到客户端,然后保存到文件。他用了 2.5 小时才成功,所以我将与您分享解决方案。

首先在客户端创建一个按钮来检索信息:

//Write the results to a file.          
        //Add an Export button
        Button btnExport = new Button("Export Details");
        btnExport.setWidth("105px");
        btnExport.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {

                java.sql.Date sqlStartDate = dateBoxStart.getValue() == null ? null : new java.sql.Date(dateBoxStart.getValue().getTime());
                java.sql.Date sqlEndDate = dateBoxEnd.getValue() == null ? null : new java.sql.Date(dateBoxEnd.getValue().getTime());

                AsyncCallback<String> callback = new PrintPackSummaryHandler<String>(PackSummaryView.this);
                rpc.printPackSummary(scoutGroupId, sqlStartDate, sqlEndDate, callback); 

            }
        });
        horizontalDatesPanel.add(btnExport);

连接是:

String printPackSummary(String groupID, Date startDate, Date endDate);

服务器端的代码是(注意:这是逗号分隔的,所以我可以将它写入 csv 文件并用 MS 打开它 Excel):

public String printPackSummary(String groupID, java.sql.Date startDate, java.sql.Date endDate) {
    HttpServletResponse resp = getThreadLocalResponse();

    List<PackSummary> list = getPackSummary(groupID, startDate, endDate);
    StringBuilder fileContent = new StringBuilder();
    for(PackSummary pack : list){
        fileContent.append(pack.getMetric()+","+pack.getMetricTotal()+"\n");
    }
    return URLEncoder.encode(fileContent.toString());
}

我在这里重新使用 SQL 来填充视图。为了完整起见,它是:

public List<PackSummary> getPackSummary(String groupID, java.sql.Date startDate, java.sql.Date endDate) {

    List<PackSummary> packSummaryList = new ArrayList<PackSummary>();
    PreparedStatement ps = null;
    // Create connection/statement variables outside of try block
    Connection c = null;

    String selectQry = ("SELECT 'Bronze Boomerang' as metric, COUNT(at_cub_awards.ca_id) as metricCount " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_name LIKE '%Bronze Boomerang%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Silver Boomerang', COUNT(at_cub_awards.ca_id) " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_name LIKE '%Silver Boomerang%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Gold Boomerang', COUNT(at_cub_awards.ca_id) " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_name LIKE '%Gold Boomerang%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Grey Wolf', COUNT(at_cub_awards.ca_id) " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_name LIKE '%Grey Wolf%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Level 1', COUNT(at_cub_awards.ca_id) " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_name LIKE '%Level 1%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Level 2', COUNT(at_cub_awards.ca_id) " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_name LIKE '%Level 2%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Special', COUNT(at_cub_awards.ca_id) " +
            "FROM at_cub_details, at_cub_awards, at_award " + 
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_cub_awards.cd_id " +
            "  AND at_cub_awards.ca_awarded_date >= ? " +
            "  AND at_cub_awards.ca_awarded_date <= ? " +
            "  AND at_cub_awards.aw_id = at_award.aw_id " +
            "  AND at_award.aw_award_type LIKE '%Special Interest%' " +
            "GROUP BY at_award.aw_award_type " +
            "UNION " +
            "SELECT 'Joined', COUNT(at_cub_details.cd_id) " +
            "FROM at_cub_details, at_section_details " +
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_section_details.cd_id " +
            "  AND at_section_details.sd_start_date >= ? " +
            "  AND at_section_details.sd_start_date <= ? " +
            "GROUP BY at_cub_details.grp_id " +
            "UNION " +
            "SELECT 'Left', COUNT(at_cub_details.cd_id) " +
            "FROM at_cub_details, at_section_details " +
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_id = at_section_details.cd_id " +
            "  AND at_section_details.sd_end_date >= ? " +
            "  AND at_section_details.sd_end_date <= ? " +
            "GROUP BY at_cub_details.grp_id " +
            "UNION " +
            "SELECT 'Current', COUNT(at_cub_details.cd_id) " +
            "FROM at_cub_details " +
            "WHERE at_cub_details.grp_id = ? " +
            "  AND at_cub_details.cd_archived IS NULL " +
            "GROUP BY at_cub_details.grp_id;");

    try {
        // Get Connection and Statement from DataSource
        c = ds.getConnection();
        ps = c.prepareStatement(selectQry);

        try {
            // Create a statement and execute the query on it               
            ps.setString(1, groupID);
            ps.setDate(2, (java.sql.Date) startDate);
            ps.setDate(3, (java.sql.Date) endDate);
            ps.setString(4, groupID);
            ps.setDate(5, (java.sql.Date) startDate);
            ps.setDate(6, (java.sql.Date) endDate);
            ps.setString(7, groupID);
            ps.setDate(8, (java.sql.Date) startDate);
            ps.setDate(9, (java.sql.Date) endDate);
            ps.setString(10, groupID);
            ps.setDate(11, (java.sql.Date) startDate);
            ps.setDate(12, (java.sql.Date) endDate);
            ps.setString(13, groupID);
            ps.setDate(14, (java.sql.Date) startDate);
            ps.setDate(15, (java.sql.Date) endDate);
            ps.setString(16, groupID);
            ps.setDate(17, (java.sql.Date) startDate);
            ps.setDate(18, (java.sql.Date) endDate);
            ps.setString(19, groupID);
            ps.setDate(20, (java.sql.Date) startDate);
            ps.setDate(21, (java.sql.Date) endDate);
            ps.setString(22, groupID);
            ps.setDate(23, (java.sql.Date) startDate);
            ps.setDate(24, (java.sql.Date) endDate);
            ps.setString(25, groupID);
            ps.setDate(26, (java.sql.Date) startDate);
            ps.setDate(27, (java.sql.Date) endDate);
            ps.setString(28, groupID);

            //Get result set
            ResultSet result = ps.executeQuery();

            while (result.next()) {
                PackSummary packSummary = new PackSummary(result.getString("metric"), result.getInt("metricCount"));
                packSummaryList.add(packSummary);
            }

            // Clean up
            ps.close();
            c.close();

        } catch (SQLException se) {
            System.out.println("SQLException in getPackSummary: " + se.toString());
        } catch (Exception e) {
            System.out.println("Errors occurred in getPackSummary: " + e.toString());
        }

    } catch (SQLException e1) {
        System.out.println("SQLException in getPackSummary: " + e1.toString());
        e1.printStackTrace();

    } finally {

        // Ensure connection is closed and returned to the pool, even if errors occur.
        // This is *very* important if using a connection pool, because after all the
        // connections are used, the application will hang on getConnection(), waiting
        // for a connection to become available.
        // Any errors from the following closes are just ignored.  The main thing is
        // that we have definitely closed the connection.
        try { if(ps != null) ps.close(); } catch (Exception e) {}
        try { if(c != null) c.close(); } catch (Exception e) {}
    }
    // Done
    return packSummaryList;

}

在 return 客户端调用以下 class 显示 window 以允许选择要保存到的路径和文件名:

class PrintPackSummaryHandler<T> implements AsyncCallback<String> {
    //Get the Pack Summary details
    PackSummaryView view;

    public PrintPackSummaryHandler(PackSummaryView view) {
        this.view = view;
    }

    public void onFailure(Throwable ex) {
        System.out.println("RPC call failed - PackSummaryView - PrintPackSummaryHandler.");
        Window.alert("Connection failed - please retry.");
    }
    public void onSuccess(String result) {
        Window.open("data:application/csv;charset=utf-8,"+result,"_parent", "location=no") ;
        System.out.println("Download succeed !!"+result);
    }
}

希望对大家有所帮助。

此致,

格林