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

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

首先在服务器搭建ftp服务

配置文件(在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<MultipartFile> 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();
    }

前端页面
<input id="file" name="file" type="file" multiple="multiple" style="margin-left:20px;margin-top:10px;"/>
ajax调用传输数据(传输文件的同时,传输其他数据)
 var form = new FormData; 
				var instrumentApplys=new Array();
				for(var i =0 ;i<document.getElementById("file").files.length;i++){                                         //创建一个FormData对象
					form.append('file',document.getElementById("file").files[i]);
				}
				form.append('pssj',$("#pssj").val());
				form.append('psjg',$('input[name="psjg"]:checked').val());
				form.append('psdd',$("#psdd").val());
				form.append('psyj',$("[name=psyj]").val());
				form.append('pszt',pszt);
				form.append('id',getUrlParam("id"));
				form.append('userid',getUrlParam("userid"));
				form.append('deptid',getUrlParam("deptid"));
				form.append('pslx',$("#pslx").val());
				form.append('proBasicInforId',getUrlParam("probasicinforid"));
				$.ajax({
					type: 'post',
					async: false,
					cache: false,
					url: urlPrev + "/proDemandProcess/dsfps",
					data: form,
					dataType: 'json',
					contentType: false,
					processData: false, 
					success: function(res) {
						if(res.code == 0) {
							hintInfo("提交成功!!");
						} else {
							hintInfo("提交失败!!");
						}
					}
				});
				

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

下载工具类
/**
	 * 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();
    }
前端页面
<div style='margin-left:100px;'><a href='http://localhost:8081/proDemandProcess/downFiles?filename="+文件名+"'  style='color:blue;' download='+文件名+'>"+文件名+"</a></div>
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值