玩! 2在heroku上使用Java,保存文件临时

时间:2013-08-14 13:44:19

标签: java heroku playframework-2.0

刚开始 - 抱歉我的英语。

我正在用java开发一个play-application并将它部署到heroku。 我喜欢创建一张图片(精确的QRCode),临时存储并在下一页显示。 我知道herokus短暂的文件系统,但如果我理解正确,在雪松堆栈上,我能够在任何我喜欢的地方创建文件,只要它没问题,它们将不会被存储很长时间。应用程序只需要生成QR,我扫描它,文件可能会被删除。

好像文件没有创建。有关如何设法临时保存并显示我的QR的任何想法?

控制器

public class Application extends Controller {

    private static String workingDirectory = "public/images/";
    public static Result qrCode() {
        String msg = "I am a QR-String";
        BufferedImage image = (BufferedImage) QR.stringToImage(msg);

        String imgPath = workingDirectory+"posQR.png";

        try{
            File outputfile = new File(imgPath);
            ImageIO.write(image,"png",outputfile);
        }catch(IOException e){
            e.printStackTrace();
        }
        return ok(views.html.qrCode.render());
    }
}

查看qrCode

<img src="@routes.Assets.at("images/posQR.png")">

编辑1

将图像存储为tempFile并将其传递给视图。 在heroku上,本地视图包含确切的绝对路径,但图像不会加载。 有什么想法吗?

控制器

public class Application extends Controller {

    private static String workingDirectory = "public/images/";
    public static Result qrCode() {
        String msg = "I am a QR-String";
        BufferedImage image = (BufferedImage) QR.stringToImage(msg);
    File outputfile = null;
        String imgPath = workingDirectory+"posQR.png";

        try{
            outputfile = File.createTempFile("posQR",".png");
            ImageIO.write(image,"png",outputfile);
        }catch(IOException e){
            e.printStackTrace();
        }
            return ok(views.html.qrCode.render(outputfile.getAbsolutePath()));
}

查看qrCode

@(qrPath: String)
...
<img id="qr" src=@qrPath>

2 个答案:

答案 0 :(得分:0)

workingDirectory是否以文件分隔符结尾?

String imgPath = workingDirectory+"posQR.png";

答案 1 :(得分:-1)

这帮助了我:Play! framework 2.0: How to display multiple image?

最后我做到了。诀窍不是src = path而是src = getImage(path)。仍然很奇怪,但现在它有效。

<强>路由

GET /tmp/*filepath  controllers.Application.getImage(filepath: String)

<强>应用

public class Application extends Controller {

public static Result qrCode() {
    String msg = "I am a QR-String";
    BufferedImage image = (BufferedImage) QR.stringToImage(msg);
    File outputfile = null;

    try{
        outputfile = File.createTempFile("posQR",".png");
        ImageIO.write(image,"png",outputfile);
    }catch(IOException e){
        e.printStackTrace();
    }
    return ok(views.html.qrCode.render(outputfile.getAbsolutePath()));
}
...

public static Result getImage(String imgPath){
    return ok(new File(imgPath));
}
}

查看qrCode

@(qrPath: String)
...
<img src="@routes.Application.getImage(qrPath)"/>

感谢您的帮助:D