2016-04-22 14 views
0

私のプロジェクトでは、upload methodの方法で画像をアップロードします。 プロジェクトディレクトリは次のとおりです。Sparkjavaフレームワークでアップロード画像のパスを取得する方法は?

Project 
    |---src/main/java 
    |---src/main/resources 
        |---static 
          |---css 
           |---default.css 
    |---upload 
     |---1.jpg 
     |---2.jpg 

ビューページはFreeMarkerのでレンダリングします。私のshowimage.ftlファイルでは、imgタグ<img src="...">、srcにアップロードされたイメージパスを定義する方法。

アップロード画像をsrc/main/resourcesに入れると、staticFileLocationという方法でアクセスできますが、画像をリソースディレクトリにアップロードすることはできません。

答えて

0

ファイルのストリームを取得し、生の応答を送信する必要があります。 要求オブジェクトに応じて柔軟なパスを取得するようにコードを変更するだけです。

try { 
    String path = "upload/1.jpg"; 
    Path p = Paths.get(path); 

    InputStream is = new FileInputStream(p.toFile()); 

    res.raw().setContentType(Files.probeContentType(p)); 
    res.raw().setHeader("Content-Disposition", "inline; filename=" + p.getFileName()); 

    byte[] buffer = new byte[1024]; 
    int len; 
    while ((len = is.read(buffer)) > 0) { 
     res.raw().getOutputStream().write(buffer, 0, len); 
    } 

    String result = IOUtils.toString(is); 
    is.close(); 
    return result.trim(); 
} catch (Exception e) { // handle the exceptions the way you want 
    logger.error("Error while getting resource", e); 
    res.status(500); 
    return ""; 
} 
関連する問題