FTP上传下载图片
ftp上传下载通用模板
- Controller层调用,返回FTP目录相对地址
@RequestMapping("uploadImg") @ResponseBody public Map<String, Object> uploadImg(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file) { // Map<String, Object> result = new HashMap<>(); // // 获取图片原名称 // String imgName = file.getOriginalFilename(); // // 图片重命名 // String reImgName = UUIDUtils.getUUID(10) + imgName.substring(imgName.lastIndexOf(".")); // //保存 // try { // byte[] bytes = file.getBytes(); // Path path = Paths.get(imagePath + reImgName); // Files.write(path, bytes); // result.put("success", 1); // result.put("message", "上传成功!"); // result.put("url", uploadImage + reImgName); // } catch (Exception e) { // result.put("success", 0); // result.put("message", "上传失败!"); // e.printStackTrace(); // } // return result; Map<String, Object> result = new HashMap<>(); try { String url = ftpUtil.upload(file.getInputStream(), file.getOriginalFilename()); result.put("success", 1); result.put("message", "上传成功!"); result.put("url", "http://127.0.0.1:9999"+url); } catch (IOException e) { result.put("success", 0); result.put("message", "上传失败!"); e.printStackTrace(); } return result; }
- FTP封装的工具类
package com.typ.blog.utils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import sun.misc.BASE64Encoder; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @Component public class FtpUtil { //ftp服务器ip地址 String FTP_ADDRESS="127.0.0.1";//如果是自己买的服务器那就写自己服务器的IP地址 //端口号 Integer FTP_PORT=21; //用户名 String FTP_USERNAME="ftptest"; //密码 String FTP_PASSWORD="ftptest"; //图片路径 String FTP_BASEPATH="/var/ftp/test/"; /** 本地字符编码 */ private static String LOCAL_CHARSET = "GBK"; // FTP协议里面,规定文件名编码为iso-8859-1 private static String SERVER_CHARSET = "ISO-8859-1"; //根据当前文件生成 文件夹 private static String getTimePath() { Date now = new Date(); DateFormat format = new SimpleDateFormat("yyyy/MM/dd/"); return format.format(now); } /** * author : wangwei * description: 使用ftp 上传文件 * date: 2019/6/5 */ public String upload(InputStream inputStream, String originName) { StringBuilder url = new StringBuilder(); FTPClient ftp = new FTPClient(); ftp.setControlEncoding("GBK"); try { int reply; ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器 ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录 reply = ftp.getReplyCode(); System.out.println("reply:" + reply); ftp.enterLocalPassiveMode();//开启被动模式,否则文件上传不成功,也不报错 String timePath = getTimePath(); String saveDir = FTP_BASEPATH + timePath; url.append(saveDir); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); createDir(ftp, saveDir); originName = UUIDUtils.getUUID(10)+originName.substring(originName.lastIndexOf(".")); url.append(originName); ftp.storeFile(originName, inputStream); inputStream.close(); ftp.logout(); } catch (IOException e) { throw new RuntimeException("文件上传失败"); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return url.toString(); } /** * * 下载图片转换成Base64 * */ public String download(String ftpUrl,String sfzh){ FTPClient ftpClient = new FTPClient(); InputStream inputStream = null; String re=null; try { ftpClient.connect(FTP_ADDRESS,FTP_PORT); ftpClient.login(FTP_USERNAME, FTP_PASSWORD); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //是否成功登录服务器 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } //跳转到指定目录 ftpClient.changeWorkingDirectory(ftpUrl); //设置被动模式,防止在Linux上,由于安全限制,可能某些端口没有开启,出现阻塞 ftpClient.enterLocalPassiveMode(); //读取图片需要添加该方法 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //5.遍历下载的目录 FTPFile[] fs = ftpClient.listFiles(); for (FTPFile ff : fs){ //解决中文乱码问题,两次解码 // byte[] bytes=ff.getName().getBytes("iso-8859-1"); // String fileName=new String(bytes,"utf-8"); // if(sfzh.equals(fileName)){ // inputStream = ftpClient.retrieveFileStream(fileName); // } byte[] bytes=ff.getName().getBytes("iso-8859-1"); String fileName=new String(bytes,"utf-8"); inputStream = ftpClient.retrieveFileStream(fileName); } if (inputStream != null) { byte[] data=null; data=new byte[inputStream.available()]; inputStream.read(data); BASE64Encoder encoder=new BASE64Encoder(); re=encoder.encode(data); } } catch (Exception e) { e.printStackTrace(); }finally{ if(ftpClient.isConnected()){ try{ ftpClient.disconnect(); }catch(IOException e){ e.printStackTrace(); } } if(null != inputStream){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return re; } // 创建文件夹,并切换到该文件夹 // 比如: hello/test //最终会切换到test 文件夹返回 private void createDir(FTPClient client, String path) throws IOException { String[] dirs = path.split("/"); for (String dir : dirs) { if (StringUtils.isEmpty(dir)) { continue; } if (!client.changeWorkingDirectory(dir)) { client.makeDirectory(dir); } client.changeWorkingDirectory(dir); } } }
-
项目实测
-
显示效果
-
在FTP服务器中查看上传的图片文件(直接从浏览器中打开)
ps:记录下载和上传的实际调用
@CrossOrigin public class FtpController { @Autowired FtpUtil fileUtil;//(就是上面的FTP封装的工具类) //图片上传 @PostMapping("/upload2") public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException { String url = fileUtil.upload(file.getInputStream(), file.getOriginalFilename()); return url; } //图片下载转base64 @GetMapping("/download") public String download(HttpServletRequest request) throws IOException { //ftp服务器的相对路径 //图片的名字 String url = fileUtil.download("var/ftp/test2021/03/17","1615967386819.jpg"); return url; } }