返回的是base64的编码的流,前端使用<img src="返回的值"/> 即可 @Transactional(readOnly = false) public synchronized List<String> copyFileByBase64(Inner inn, String pages, Long lTime, HttpServletRequest request,StringBuffer filesN) throws Exception { List<Path> list = null; FTPClient ftp = null; List<String> fileNames = null; try{ if (inn != null) { String filePath = inn.getFilepath().replace("\\", File.separator); //从数据库中获取FTP账号密码信息 替换成自己的就行 list=printApplyDao.getPaths(filePath.substring(0, filePath.indexOf(File.separator))); } if (list != null && list.size() > 0) { //FTP登录 替换成自己的就行 ftp = archivesService.getFtpClient(list.get(0)); } if (ftp != null && !StringUtils.isEmpty(pages)) { String[] page = pages.split(","); String innerPath = inn.getFilepath().replace("\\", "/"); String path = innerPath.substring(innerPath.indexOf("/") + 1); //设置主动模式,防止在Linux上,由于安全限制,可能某些端口没有开启,出现阻塞 ftp.enterLocalPassiveMode(); //ftp上的路径 path = new String(path.getBytes("gbk"),"iso-8859-1"); boolean changeWorkingDirectory = ftp.changeWorkingDirectory(path); //判断ftp目录是否切换成功 if(changeWorkingDirectory){ FTPFile[] files = ftp.listFiles(); //对ftp文件进行排序,顺序排序 Arrays.sort(files, new MySort()); //将page字符串,转为数组 List<Integer> listPage = convertToInt(page); String fileName = null; fileNames = new ArrayList<String>(); ByteArrayOutputStream bos = null; for (Integer p : listPage) { long start = System.currentTimeMillis(); if(p>=1){ //获取ftp上的文件名称 fileName = files[p - 1].getName(); }else{ fileName = files[p - 0].getName(); } //获取文件流 InputStream retrieveFileStream = ftp.retrieveFileStream(new String(fileName.getBytes("gbk"), "ISO-8859-1")); filesN.append(fileName); if (null == retrieveFileStream) { throw new FileNotFoundException(fileName); } bos = new ByteArrayOutputStream(); int length; byte[] buf = new byte[2048]; while (-1 != (length = retrieveFileStream.read(buf, 0, buf.length))) { bos.write(buf, 0, length); } ByteArrayInputStream fis = new ByteArrayInputStream(bos.toByteArray()); bos.flush(); bos.close(); byte[] buffer = new byte[fis.available()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } if (offset != buffer.length) { throw new IOException("Could not completely read file "); } fis.close(); String asB64 = "data:image/jpg;base64,"+new Base64Encoder().encode(buffer); fileNames.add(asB64); long end = System.currentTimeMillis(); System.out.println(end-start); retrieveFileStream.close(); ftp.completePendingCommand(); } } } }catch (Exception e) { e.printStackTrace(); }finally{ if(ftp!=null&&ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return fileNames; }
不要忘了添加jar包哦
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.0.9</version> </dependency>
辛苦编码,希望可以得到支持,继续下去。