springboot文件上传、下载使用ftp工具将文件上传至服务器

springboot文件上传、下载使用ftp工具

推荐一款ftp客户端工具:iis7服务器管理工具
IIs7服务器管理工具可以批量管理ftp站点,同时具备定时上传下载的功能。
作为服务器集成管理器,它最优秀的功能就是批量管理windows与linux系统服务器、vps。能极大的提高站长及服务器运维人员工作效率。同时iis7服务器管理工具还是vnc客户端,服务器真正实现了一站式管理,可谓是非常方便。
下载地址:http://yczm.iis7.com/?tscc
使用截图如下:

springboot文件上传、下载使用ftp工具将文件上传至服务器_第1张图片

配置文件(在application.properties中)


# Single file max size  
multipart.maxFileSize=100Mb
# All files max size  
multipart.maxRequestSize=100Mb

#ftp use
ftp.server = www.datasvisser.cn
ftp.port = 41023
ftp.userName = jntechFTP1
ftp.userPassword =MUMjh3E+*=aC4\0

工具类1

/**
 * ftp上传,并将访问地址和上传的文件返回给调用者
 * 
 * @author Administrator
 *
 */
public class FtpUpload {
	/*
	 * private static String server = "www.datasvisser.cn"; //地址 private static
	 * int port = 41023;//端口号 private static String userName = "jntechFTP1";//登录名
	 * private static String userPassword ="MXUsssMjhssE+*=a3C4\\0";//密码
	 */ private static String ftpPath = "uploadFiles"; // 文件上传目录
	private static FTPClient ftpClient = new FTPClient();
	private static String LOCAL_CHARSET = "GBK";
	private static String SERVER_CHARSET = "ISO-8859-1";
	private final static String localpath = "F:/";//下载到F盘下
	private final static String fileSeparator = System.getProperty("file.separator");

/*
*文件上传工具方法
*/
	public static boolean upload(MultipartFile uploadFile, HttpServletRequest request, String server, int port,
			String userName, String userPassword, Integer id) {
		boolean result = false;
		try {
			request.setCharacterEncoding("utf-8");
			ftpClient.connect(server, port);
			ftpClient.login(userName, userPassword);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			mkDir(ftpPath);// 创建目录
			// 设置上传目录 must
			ftpClient.changeWorkingDirectory("/" + ftpPath);
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
				LOCAL_CHARSET = "UTF-8";
			}
			String fileName = new String(uploadFile.getOriginalFilename().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
			fileName = id + "-" + fileName;// 构建上传到服务器上的文件名 20-文件名.后缀
			FTPFile[] fs = ftpClient.listFiles(fileName);
			if (fs.length == 0) {
				System.out.println("this file not exist ftp");
			} else if (fs.length == 1) {
				System.out.println("this file exist ftp");
				ftpClient.deleteFile(fs[0].getName());
			}
			InputStream is = uploadFile.getInputStream();
			result = ftpClient.storeFile(fileName, is);
			is.close();
		} catch (IOException e) {
			result = false;
			e.printStackTrace();
		} finally {
			try {
				ftpClient.disconnect();
				System.out.println("上传完成。。。");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
/*
*文件下载工具方法
*/
	public static byte[] downFileByte(String remotePath ,String fileName,String server,int port,String userName,String userPassword) throws Exception {
		ftpClient.connect(server, port);
		ftpClient.login(userName, userPassword);
		ftpClient.enterLocalPassiveMode();
		if(remotePath!=null && !remotePath.equals("")){
    		ftpClient.changeWorkingDirectory(remotePath);
    		System.out.println("file success");
		}
		byte[] return_arraybyte = null;
		if (ftpClient != null) {
			try {
				FTPFile[] files = ftpClient.listFiles();
				for (FTPFile file : files) {
					String f=new String(file.getName().getBytes("iso-8859-1"),"utf-8");//防止乱码
					System.out.println(f);
					System.out.println(f.equals(fileName));
					if (f.equals(fileName)) {
						InputStream ins = ftpClient.retrieveFileStream(file.getName());//需使用file.getName获值,若用f会乱码
						ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
						byte[] buf = new byte[204800];
						int bufsize = 0;
						while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {
							byteOut.write(buf, 0, bufsize);
						}
						return_arraybyte = byteOut.toByteArray();

						File localFile = new File(localpath +fileSeparator+ f);
						OutputStream is = new FileOutputStream(localFile);
						ftpClient.retrieveFile(f, is);
						is.close();
						byteOut.close();
						ins.close();
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeConnect();
			}
		}
		return return_arraybyte;
	}

	
	 public static void closeConnect(){
	    	try{
	    		ftpClient.disconnect();
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	 }
	/**
	 * 选择上传的目录,没有创建目录
	 * 
	 * @param ftpPath
	 *            需要上传、创建的目录
	 * @return
	 */
	public static boolean mkDir(String ftpPath) {
		if (!ftpClient.isConnected()) {
			return false;
		}
		try {
			// 将路径中的斜杠统一
			char[] chars = ftpPath.toCharArray();
			StringBuffer sbStr = new StringBuffer(256);
			for (int i = 0; i < chars.length; i++) {
				if ('\\' == chars[i]) {
					sbStr.append('/');
				} else {
					sbStr.append(chars[i]);
				}
			}
			ftpPath = sbStr.toString();
			// System.out.println("ftpPath:" + ftpPath);
			if (ftpPath.indexOf('/') == -1) {
				// 只有一层目录
				ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
				ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
			} else {
				// 多层目录循环创建
				String[] paths = ftpPath.split("/");
				for (int i = 0; i < paths.length; i++) {
					ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
					ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}

工具类2

/**
 * 从配置文件里面获取值 通过key来获取value
 * @author Administrator
 *
 */
public class PropertiesUtil {
	private static Logger log=LoggerFactory.getLogger(PropertiesUtil.class);
	private static  Properties properties;
	private static final String name="application.properties";
	static {
		try {
			properties=new Properties();
			properties.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(name), "utf-8"));
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
			log.error("IOException"+e);
		}
	}
	
	public static String  getValue(String key) {
		String value=properties.getProperty(key).trim();
		if(value==null) {
			return	null;
		}
		return value;
	}
	
	
	public static String  getValue(String key,String defaultvalue) {
		String value=properties.getProperty(key).trim();
		if(value==null) {
			value=defaultvalue;
		}
		return value;
	}
}

调用(此处为多文件上传)

 @RequestMapping(value = "/dsfps",produces="application/json;charset=UTF-8")
    public  ServerResponse dsfps(@RequestParam("file") MultipartFile file,HttpServletRequest request,Integer proBasicInforId,Integer userid,Integer deptid,Integer id,Integer psjg,String pszt,String pslx,String pssj,String psdd,String psyj){
        long ids= new Date().getTime();//时间戳.后缀 的文件
        List files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filename=null;
        for (MultipartFile m:files
        ) {
        FtpUpload.upload(m, request, PropertiesUtil.getValue("ftp.server"),
                Integer.parseInt(PropertiesUtil.getValue("ftp.port")),
                PropertiesUtil.getValue("ftp.userName"),
                PropertiesUtil.getValue("ftp.userPassword"), ids);
                 filename= ids+"-"+m.getOriginalFilename()+","+filename;
                }

   return  proDemandProcessService.dsfps( proBasicInforId, userid, deptid, id, psjg, pszt, pslx, pssj, psdd, psyj,filename);
    }

文件下载

    /**
     * 文件的下载
     * @param filename
     * @return
     * @throws Exception
     */
    @RequestMapping("/downFiles")
    public  ServerResponse  downFiles(String filename) throws Exception {
        String[] split = filename.split(",");
        for (String s:split) {
            System.out.println(s);
        if(s!=null){
            FtpUpload.downFileByte("uploadFiles",s,
                    PropertiesUtil.getValue("ftp.server"),
                    Integer.parseInt(PropertiesUtil.getValue("ftp.port")),
                    PropertiesUtil.getValue("ftp.userName"),
                    PropertiesUtil.getValue("ftp.userPassword")
            );
        }
        }


        return  ServerResponse.createBySuccess();
    }

前端页面


ajax调用传输数据(传输文件的同时,传输其他数据)

 var form = new FormData; 
				var instrumentApplys=new Array();
				for(var i =0 ;i

另外一种前端页面显示下载弹出框

下载工具类
/**
	 * ym下载工具类(前端页面显示下载)
	 * @param remotePath
	 * @param fileName
	 * @param server
	 * @param port
	 * @param userName
	 * @param userPassword
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public static byte[] downFileByte(String remotePath , String fileName, String server, int port, String userName, String userPassword, HttpServletResponse response) throws Exception {
		ftpClient.connect(server, port);
		ftpClient.login(userName, userPassword);
		ftpClient.enterLocalPassiveMode();
		if(remotePath!=null && !remotePath.equals("")){
			ftpClient.changeWorkingDirectory(remotePath);
			System.out.println("file success");
		}
		byte[] return_arraybyte = null;
		String localName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");
		response.setContentType("application/octet-stream");
        response.setContentType("application/OCTET-STREAM;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+localName);

		if (ftpClient != null) {
			try {
				FTPFile[] files = ftpClient.listFiles();
				for (FTPFile file : files) {
					String f=new String(file.getName().getBytes("iso-8859-1"),"utf-8");//防止乱码
					if (f.equals(fileName)) {
						InputStream ins = ftpClient.retrieveFileStream(file.getName());//需使用file.getName获值,若用f会乱码
						//ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
						OutputStream os=response.getOutputStream();
						byte[] buf = new byte[204800];
						int bufsize = 0;
						while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {
							os.write(buf, 0, bufsize);
						}
						os.flush();
						os.close();
						ins.close();
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeConnect();
			}
		}
		return return_arraybyte;
	}
controller中的代码
@RequestMapping("/downFiles")
    public  ServerResponse  downFiles(String filename, HttpServletResponse response) throws Exception {
        String[] split = filename.split(",");
        for (String s:split) {
        if(s!=null){
            FtpUpload.downFileByte("uploadFiles",s,
                    PropertiesUtil.getValue("ftp.server"),
                    Integer.parseInt(PropertiesUtil.getValue("ftp.port")),
                    PropertiesUtil.getValue("ftp.userName"),
                    PropertiesUtil.getValue("ftp.userPassword"),response
            );
        }
        }
        return  ServerResponse.createBySuccess();
    }
前端页面

你可能感兴趣的:(springboot文件上传、下载使用ftp工具将文件上传至服务器)