簡體   English   中英

玩! 2在heroku上使用Java,臨時保存文件

[英]Play! 2 with Java on heroku, save file temporary

一開始-對不起我的英語。

我正在用Java開發一個播放應用程序並將其部署到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());
    }
}

查看二維碼

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

查看二維碼

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

workDirectory是否以文件分隔符結尾?

String imgPath = workingDirectory+"posQR.png";

這幫助了我: 玩! Framework 2.0:如何顯示多個圖像?

最后,我做到了。 訣竅不是執行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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM