1

私のBeanには次のような関数があります。

public String uploadFile(UploadedFile uploadedFile) {
    logger.info("Enter: uploadFile(UploadedFile uploadedFile).");
    String name = uploadedFile.getName();
    String extension = name.substring(name.length() - 3);
    if (extension.contentEquals("peg")) {
        extension = "jpeg";
    }

    RandomString rs = new RandomString(RANDOM_PHOTO_NAME_LENGTH);
    this.randomPhotoName = rs.nextString();

    String fileName = this.randomPhotoName + "." + extension;
    logger.info("File name: " + name + ". Extension: " + extension + ". New fileName: " + fileName);
    ServletContext sc = (ServletContext) FacesContext.getCurrentInstance()
            .getExternalContext().getContext();

    File f = new File(
            sc.getRealPath(Constant.USER_FILE_PATH));
    if (!f.exists()) {
        logger.info("Folder "
                + Constant.USER_FILE_PATH
                + " nie istniej. Tworze nowy.");
        f.mkdirs();
    }
    File backupFile = new File(
            sc.getRealPath(Constant.USER_FILE_PATH
                    + fileName));

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new BufferedInputStream(uploadedFile.getInputStream());
        out = new FileOutputStream(backupFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
    } catch (IOException ioe) {
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage msg = null;
        msg = new FacesMessage(
                "Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.");

        context.addMessage(null, msg);
        logger.error(
                "Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.",
                ioe);
    } finally {
        try {
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    logger.info("Exit: uploadFile(UploadedFile uploadedFile).");
    return fileName;
}

そして、すべてのファイルはtmpディレクトリに保存されます。例:

\jboss-5.1.0.GA\server\default\tmp\a006-czo4uq-gzzu4l42-1-gzzuk7xr-a2\TupTus.war\media\img\user-gallery\6u2fpgu3tkzniwg.JPG
4

1 に答える 1

4

すべてのファイルは次のように構築されているため:

File backupFile = new File(
            sc.getRealPath(Constant.USER_FILE_PATH
                    + fileName));

sc.getRealPath()JBossがアプリケーションに割り当てる作業ディレクトリを返すように聞こえます。

だから、本当の質問はあなたにあります:あなたはどこにファイルを書きたいですか?そこにない場合は、どこですか?ユーザーの一時ディレクトリを使用したい場合はnew File(System.getProperty("java.io.tmpdir"), fileName)、そこに書き込んでください。

箱から出してパスを設定できるようにしたい場合は、このパスをDBまたは設定ファイルに保存するか、コマンドラインスイッチを使用してJBossを実行しているときにカスタムシステムプロパティを介して渡すことができます-D

于 2012-03-19T19:08:41.160 に答える