Openshift:如何从DATA_DIR显示图像?

时间:2015-01-10 20:16:45

标签: java servlets openshift

根据[https://stackoverflow.com/a/24264878/2382770][1]答案(不接受)我尝试从OpenShift DATA_DIR读取图像文件,但在浏览器中获取消息:

  

图片«http://app-name.rhcloud.com/GetImageServlet?img=681265.jpg»   因为包含错误而无法显示。“

@WebServlet("/GetImageServlet")
public class GetImageServlet extends HttpServlet {

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

        String fileName = request.getParameter("img");
        String uploadFilePath = ...;
        System.out.println(uploadFilePath);

        byte[] imageBytes = getImageAsBytes(uploadFilePath);
        response.setContentType("image/jpeg");
        response.setContentLength(imageBytes.length);
        response.getOutputStream().write(imageBytes);
    }

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

    public byte[] getImageAsBytes (String ImageName) throws IOException {
         // open image
         File imgPath = new File(ImageName);
         BufferedImage bufferedImage = ImageIO.read(imgPath);

         // get DataBufferBytes from Raster
         WritableRaster raster = bufferedImage .getRaster();
         DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

         return ( data.getData() );
    }

    private static final long serialVersionUID = 1L;
}

我们真的可以从OpenShift DATA_DIR获取数据吗?

1 个答案:

答案 0 :(得分:2)

您犯的唯一错误是发送RAW图像数据(由ImageIO读取)。更改getImageAsBytes()方法以使用标准FileInputStream直接从文件中读取图像数据(例如,jpeg文件包含以jpeg格式编码的图像)。或者,您可以使用“Files.readAllBytes(..)”来阅读文件内容。