在瀏覽器預覽服務器上的圖片(知道路徑就行,不一定非得服務器上的)


不多說,當知道文件的存放路徑時,只需要給這個傳要給路徑就行了,代碼如下ort java.io.ByteArrayOutputStream;

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標簽直接使用就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM