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

时间:2015-03-23 00:42:09

标签: java gwt

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

// 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
}

我选择的文件是C:\ Users \ Glyndwr \ Documents \ file5-test.txt 打印的文件路径及其创建位置为C:\ Tomcat \ webapps \ awardtracker_n \ file5-test.txt

2 个答案:

答案 0 :(得分:0)

这不是完全你要求的是什么?

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

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

答案 1 :(得分:0)

答案是由同事提供的,并采取不同的方法。获取服务器端的信息,将其返回到客户端,然后将其保存到文件中。他花了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;

}

返回客户端时,调用以下类,该类显示一个窗口,允许选择要保存到的路径和文件名:

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);
    }
}

我希望这对某人有帮助。

此致

格林