我在FTP中保存用户上传的图像。
FTP服务正在服务器Server-A
上运行。实际问题是,当我想看到从本地主机上运行的Web应用程序上传的图像时,一切正常,但是当我将本地应用程序部署到运行在同一服务器Server-A
上的Tomcat时,图像无法正确显示。
我在本地Tomcat中运行Web应用程序时的图片:
在远程Tomcat中运行Web应用程序时的相同图片:
您可以看到第二张图片显示不正确。还要提一下FTP是一样的。
我使用Spring与Apache FtpClient库进行图像上传/下载功能。
控制器源代码:
@RequestMapping(value = "/{id:\\d+}/image", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
protected byte[] getUserImage(BaseForm form,
@PathVariable("id") int userId) {
try {
User user = checkToken(form.getToken());
log.info("/users/{id}/image [GET]. User: " + user + ", form: " + form + ", User id: " + userId);
FileWrapper image = service.getUserImage(userId);
if(image != null) {
return ftpService.downloadFtpFile(image.getName());
}
}
catch(Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
FtpService源代码:
public byte[] downloadFtpFile(String filePath) throws IOException {
FTPClient client = new FTPClient();
try {
client.connect(host, port);
if(!client.login(username, password)) {
throw new AdminException("Invalid ftp username/password");
}
client.enterLocalPassiveMode();
try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
client.retrieveFile(filePath, outputStream);
return outputStream.toByteArray();
}
}
catch(Exception e) {
log.error(e.getMessage(), e);
}
finally {
if(client.isConnected()) {
client.logout();
client.disconnect();
}
}
return null;
}
提前致谢!
答案 0 :(得分:1)
如果您没有将FTP传输设置为二进制(而不是ASCII),它将"转换行结尾" (或它认为是行结尾的东西)会破坏图片。