我在Spring Controller中有此方法,但我想确保不要造成内存泄漏。是还是不是?

@ResponseBody
@RequestMapping(value = "/document/{id}/{filename:.*}", method = RequestMethod.GET)
public byte[] getDownloadEclaimsDocument(@PathVariable("id") final String id, @PathVariable("filename") final String fileName, final HttpServletResponse response) {
    final DmsFile dmsFile = dmsService.getByFileSystemId(id);
    response.setContentType(dmsFile.getContentType());
    // This call gets a byte[] from a backend service
    return dmsService.getFileAsByteArray(dmsFile);
}

最佳答案

也许最好使用org.springframework.core.io.Resource

@ResponseBody
@RequestMapping(value = "/document/{id}/{filename:.*}", method = RequestMethod.GET)
public Resource getDownloadEclaimsDocument(@PathVariable("id") final String id,
        @PathVariable("filename") final String fileName,
        final HttpServletResponse response,) {
    final DmsFile dmsFile = dmsService.getByFileSystemId(id);
    byte[] data = dmsService.getFileAsByteArray(dmsFile);

    response.setContentType(dmsFile.getContentType());
    response.setContentLength(data.length);
    response.setHeader("Content-Disposition",
                       "attachment; filename=\"" +
                       MimeUtility.encodeWord(dsmFile.getName(), "utf-8", "Q") + "\"");

    // This call gets a byte[] from a backend service
    return new ByteArrayResource(data);
}

关于java - 直接从Spring Controller返回byte []是否会造成内存泄漏?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36763376/

10-08 21:46