将文件复制到文件夹

时间:2017-07-04 14:40:33

标签: java file jsp file-upload

我有这个:

在addMusic.jsp中:

<form method="post" action="Handler" enctype="multipart/form-data">
    <div class="form-group">
        <label>Musica:</label> 
        <input type="text" class="form-control" name="add_musica_nome" placeholder="Nome Musica">
    </div>
    <div class="form-group">
        <label>Localização:</label>
        <input type="file" class="form-control" name="add_musica_path" accept="audio/*">
    </div>
    <div class="form-group">
        <label>Ano:</label>
        <input type="text" class="form-control" name="add_musica_ano" pattern="[0-9]{4,4}">
    </div>
    <div class="form-group">
        <input type="hidden" name="logica" id="logica" value="SMusica"/>
        <input  type="hidden" name="acao" id="acao" value="addMusica"/> 
        <input class="btn btn-success" type="submit" value="Inserir" name="inserir"/>
    </div>
</form>

In Handler:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String parametro = request.getParameter("logica"); // Recebe como parametro do jsp, qual a class do service que
                                                        // irá atuar
    String nomeDaClasse = "services." + parametro; // Nome da Classe

    try {
        Class<?> classe = Class.forName(nomeDaClasse);
        Logica logica = (Logica) classe.newInstance();

        String pagina = logica.executa(request, response);
        request.getRequestDispatcher(pagina).forward(request, response);

    } catch (Exception e) {
        throw new ServletException("A lógica causou uma exceção", e);
    }
}

和SMusica:

final String Dest = "/data/";

public void addMusica(String musica_nome, Part musica, String ano) throws IOException {

    String fileName = Paths.get(musica.getSubmittedFileName()).getFileName().toString(); // MSIE fix.

    try {

        File music = new File(fileName);

        System.out.println("Path: " + music.getAbsolutePath());

        if (music.renameTo(new File(Dest + music.getName()))) {
            System.out.println("File is moved successful!");
        } else {
            System.out.println("File is failed to move!");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {

    if (req.getParameter("acao").equals("addMusica")) {
        addMusica(req.getParameter("add_musica_nome"), req.getPart("add_musica_path"),
                req.getParameter("add_musica_ano"));
    }
    return "/index.jsp";
}

我打印了一段绝对音乐(文件),然后它返回C:\ Users \ Fabio \ Desktop \ eclipse \ ProfJam _-_ Mortalhas.mp3,而不是真正的路径。

我的问题是如何才能获得文件的真实路径?

1 个答案:

答案 0 :(得分:1)

路径中有一个名为

的方法
  Path _rp = p.toRealPath();

也许你可以朝这个方向搜寻