我的Grails应用程序连接到另一个Grails应用程序,如果.pdf是单个页面文件,则将.pdf文件转换为.png;如果.pdf文件包含多个页面,则将其转换为.png的.zip。这是转换器的代码:
class PdfToPngController {
def converterService
def convert() {
File originalFile = ...
File converted = converterService.convert(originalFile, "png")
InputStream inputStream = converted.newInputStream()
response.outputStream << inputStream
response.setContentLength(Long.valueOf(converted.length()).intValue())
response.setCharacterEncoding("UTF-8")
String mimeType
if(converted.endsWith(".png")) {
mimeType = "image/png"
}
else if(converted.endsWith(".zip")) {
mimeType = "application/zip"
}
response.contentType = mimeType
response.setHeader("Content-type", mimeType)
response.setContentType(mimeType)
response.setHeader("Content-disposition", "inline;filename=${converted.getName()}")
inputStream.close()
}
}
我的应用程序将发送pdf文件,并等待转换后的文件作为响应,问题是当我尝试获取响应的内容类型时,它返回null
。这是我的应用程序上的RESTClient:
RESTClient client = new RESTClient(grailsApplication.config.report.converter.base)
client.request(Method.POST) { multipartRequest ->
uri.path = grailsApplication.config.report.converter.path
// ...
response.success = { response, data ->
if(response.getStatus() == HttpServletResponse.SC_OK) {
println "getContentType: ${response.getEntity().getContentType()}"
// This prints
// getContentType: null
String extension
if(response.getEntity().getContentType() == "image/png")) {
extension = "png"
}
else if(response.getEntity().getContentType() == "application/zip")) {
extension = "zip"
}
OutputStream outputStream = new ByteArrayOutputStream()
response.entity.writeTo(outputStream)
byte[] byteArray = outputStream.toByteArray()
digest = md5.digest(byteArray)
hashedFilename = new BigInteger(1, digest).toString(36)
FileUtils.writeByteArrayToFile(new File(thumbnailsDir.getAbsolutePath() +
File.separator + hashedFilename +
"." + extension), byteArray)
outputStream.close()
}
else if(HttpServletResponse.SC_CREATED) {
throw new ConnectException("The report service failed to convert it to .png.")
}
}
}
为什么我的应用程序无法确定响应的contentType
?转换器应用程序是否将contentType
设置为错误?还是在确定contentType
时使用了错误的方法?还是转换应用程序的错误?