不多说,当知道文件的存放路径时,只需要给这个传要给路径就行了,代码如下
package ArrayTest; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class DownLoadFile { private String downloadFile(String filepath)throws Exception{ String re = null; String url = null; FtpClientFactory factory = null; FtpClient ftpclient=null; InputStream is = null; try { factory = getFtpFactory(); ftpclient = factory.makeobject(); //下载目录和文件 String prefix = "ftp:/"+ftpclient.getRemoteAddress(); filepath = filepath.replace(prefix,""); int index = filepath.lastIndexOf("/"); String dirpath = filepath.substring(0,index+1); String fileName = filepath.substring(index+1); ftpclient.changeWorkingDirectory(dirpath); //验证文件是否存在 if(!FtpUtil.existDirectory(ftpclient,dirpath)||!FtpUtil.existFile(ftpclient,dirpath,fileName)) { throw new IllegalStateException("文件不存在或者已被删除!"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); is=ftpclient.retrieveFileStream(fileName); System.err.println("is:"+is.available()); byte[] buf = new byte[20000]; byte[] data = new byte[200000]; int len = 0; int offset = 0; while((len=is.read(buf))!=-1) { /** * 数组容量不够,开始扩容 */ if(offset+len>=data.length) { byte[] tmp = new byte[data.length]; System.arraycopy(data, 0, tmp, 0, data.length); data=tmp; /** * 文件大于3M,提示超时(可不写,因为公司电脑太差,大了容易卡住) */ if(tmp.length>3000000) { return "超时"; } } System.arraycopy(buf, 0, data, offset, len); offset+=len; } BASE64Encoder encoder = new BASE64Encoder(); re=encoder.encoder(data); url="data:image/jpeg;base64"+re.replace("\r\n", ""); } catch (Exception e) { e.printStackTrace(); throw new Exception(e.getMessage()); }finally { try { if (is != null) is.close(); if (!ftpclient.completePendingCommad()) { ftpclient.logout(); ftpclient.disconnect(); } } catch (Exception e2) { e2.printStackTrace(); } } return url; } }
在前端通过img标签直接使用就可以了。
在浏览器预览服务器上的图片(知道路径就行,不一定非得服务器上的)
原文:https://www.cnblogs.com/Mr-RanX/p/11436349.html