從FTP下載圖片返回檔案流在頁面顯示圖片
.HTML
<div id="showPicture" style="width:100%;height:800px;line-height:100px;overflow:auto;overflow-x:hidden; text-align: center;">
</div>
.JS
$("#showPicture").append("<img src='/SREHR/web/common/getFtpImage?filepath="+filepath+"' width='900px' height='675px' title=''/>");
.Controller
@RequestMapping("getFtpImage")
@ResponseBody
public void getFtpImage (String workId,HttpServletResponse response,@RequestParam String filepath) throws InterruptedException {
//建立FTP連線
FTPClient ftp = null;
OutputStream outStream = null;
InputStream in = null;
try {
ftp= initFTP(ftp);
//下載檔案
in = ftp.retrieveFileStream(filepath);
String picType = filepath.split("\\.")[1];
BufferedImage bufImg = null;
bufImg = ImageIO.read(in);
outStream = response.getOutputStream();
ImageIO.write(bufImg, picType, outStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in!=null) {
try {
in.close();
destroy(ftp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//FTP初始化
public FTPClient initFTP(FTPClient ftp) throws IOException {
InputStream in = UploadToFtpController.class.getResourceAsStream("/application.properties");
Properties properties=new Properties();
properties.load(in);
String addr = properties.getProperty("ftp_url");
int port=Integer.valueOf(properties.getProperty("ftp_port")).intValue();
String username=properties.getProperty("ftp_username");
String password=properties.getProperty("ftp_password");
ftp = new FTPClient();
ftp.connect(addr,port);
ftp.login(username,password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setControlEncoding("GBK");
ftp.setBufferSize(1024*1024*10); //設定緩衝區上傳速度為10M,預設為1K
ftp.setFileType(FTP.BINARY_FILE_TYPE);//設定上傳方式位位元組
ftp.enterLocalPassiveMode();//Switch to passive mode
return ftp;
}
//關閉FTP
public void destroy(FTPClient ftp) throws IOException {
if(ftp != null){
ftp.disconnect();
ftp = null;
}
}