Image 服务器给出500代码错误,但仍提供内容

Image 服务器给出500代码错误,但仍提供内容,image,api,http,uploading,spark-java,Image,Api,Http,Uploading,Spark Java,我正在为“serveraddress/img/:imageid”提供以下功能: public static String getImage(Request req, Response res) { String imageId = req.params("imageid"); byte[] bytes = readImage("img/" + imageId); return Base64.getMimeEncoder().encodeToSt

我正在为“serveraddress/img/:imageid”提供以下功能:

 public static String getImage(Request req, Response res) {
        String imageId = req.params("imageid");
        byte[] bytes = readImage("img/" + imageId);

        return Base64.getMimeEncoder().encodeToString(bytes); 
    }

 public static byte[] readImage(String image) {
        byte[] bytes;
        try {
            File fff = new File(image);
            FileInputStream fileInputStream = new FileInputStream(fff);
            long byteLength = fff.length();

            bytes = new byte[(int) byteLength];
            fileInputStream.read(bytes, 0, (int) byteLength);
        } catch (Exception ex) {
            ex.printStackTrace();
            bytes = null;
        }
        return bytes;
    }
public static void main(String[] args) {
        BasicConfigurator.configure();
        org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR);
        port(8883);
        get("/img/:imageid", this::getImage);
}
对于前两个请求,它会正常交付。但当更多的请求(如5或6个请求)请求图像时,它开始发送服务器错误代码500,而没有任何堆栈跟踪。我不确定是什么问题,但我希望有人能帮我弄清楚

下面是我的gradle.build文件,供任何想要测试它的人使用:

testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.21'
compile "com.sparkjava:spark-core:2.7.1"
这也是主要功能:

 public static String getImage(Request req, Response res) {
        String imageId = req.params("imageid");
        byte[] bytes = readImage("img/" + imageId);

        return Base64.getMimeEncoder().encodeToString(bytes); 
    }

 public static byte[] readImage(String image) {
        byte[] bytes;
        try {
            File fff = new File(image);
            FileInputStream fileInputStream = new FileInputStream(fff);
            long byteLength = fff.length();

            bytes = new byte[(int) byteLength];
            fileInputStream.read(bytes, 0, (int) byteLength);
        } catch (Exception ex) {
            ex.printStackTrace();
            bytes = null;
        }
        return bytes;
    }
public static void main(String[] args) {
        BasicConfigurator.configure();
        org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR);
        port(8883);
        get("/img/:imageid", this::getImage);
}

看起来您的代码从未关闭它使用的
文件
输入流
,因此您正在泄漏文件描述符和内存。您应该使用try-with-resources或在finally块中关闭它们(顺便说一句,也许您可以使用linter警告您未关闭的资源)。

看起来您的代码从未关闭它使用的
文件或
输入流,因此您正在泄漏文件描述符和内存。您应该使用try-with-resources或在finally块中关闭它们(另外,您可以使用linter警告您未关闭的资源)