java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)

初学java,大神路过看看就好,如果有问题请多多指教,谢谢

一、效果演示

java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第1张图片
1、查看ftp站点的物理路径中的文件
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第2张图片
2、点击提交之后新增一条用户信息数据,将图片文件上传到ftp服务器上
在这里插入图片描述
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第3张图片

二、java代码实现

2.1、首先要自己新建一个maven项目,具体在上一篇博客有讲到
2.2、新建一个ftp服务器的资源文件ftp.properties
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第4张图片
资源文件的内容:

#启动双协议,8083用于ftp上传,8083用于查看(这样不需要输入ftp账号密码)
localhost=127.0.0.1
#ftp上传端口
port=2121
ftpUserName=test
ftpPassword=123
ftpPath=ftp

#http协议查看用户图片端口
ftpLookPort=2121

#ftp查看用户图片链接
ftpLookUrl=http://127.0.0.1:8083

#本地图片的保存路径
userFilePath=/userImage/

在spring-mybatis配置文件中加载
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第5张图片
然后打开iis服务管理然后
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第6张图片
点击添加
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第7张图片
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第8张图片
将上传文件所需要的工具类封装到util包里面
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第9张图片
1、FTP_Upload_Download(文件上传)类

package com.ysm.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * @author admin
 * 
 */
@Component
public class FTP_Upload_Download {

	// 读取ftp.property文件属性值

	/**
	 * 主机ip
	 */
	@Value("${localhost}")
	private String localhost;

	/**
	 * 上传端口
	 */
	@Value("${port}")
	private int port;

	/**
	 * 用户名
	 */
	@Value("${ftpUserName}")
	private String ftpUserName;

	/**
	 * 密码
	 */
	@Value("${ftpPassword}")
	private String ftpPassword;

	/**
	 * 默认地址
	 */
	@Value("${ftpPath}")
	private String ftpPath;
	
	/**
	 * ftp查看端口
	 */
	@Value("${ftpLookPort}")
	String lookPort;
	/**
	 * ftp查看链接
	 */
	@Value ("${ftpLookUrl}")
	String ftpLookUrl;
	
	/**
	 * 用户图片上传的路径
	 */
	@Value("${userFilePath}")
	String userFilePath;
	

	public final String getUserFilePath() {
		return userFilePath;
	}

	public final void setUserFilePath(String userFilePath) {
		this.userFilePath = userFilePath;
	}

	@Value("${folderName}")
	 String folderName;

	
	@Value("${processFilePath}")
	String processFilePath;
    


	/**
	 * 获取FTPClict对象
	 * 
	 * @param localhost
	 *            主机
	 * @param port
	 *            端口
	 * @param ftpUserName
	 *            ftp用户名
	 * @param ftpPasswork
	 *            ftp密码
	 * @param ftpPath
	 *            ftp工作路径
	 * @return
	 */
	
	private FTPClient getFTPClient(String localhost, int port, String ftpUserName, String ftpPasswork, String ftpPath) {
		FTPClient ftpClient = new FTPClient();
		try {
			// 连接ftp
			ftpClient.connect(localhost, port);
			ftpClient.login(ftpUserName, ftpPasswork);
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				// 取消连接
				ftpClient.disconnect();
				return null;
			}
			// 中文支持
			ftpClient.setControlEncoding("UTF-8");
			// 二进制
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(ftpPath);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return ftpClient;
	}

	/**
	 * ftp上传
	 * 
	 * @param fileName
	 *            保存ftp文件名称
	 * @param file
	 *            要上传的文件
	 */
	public boolean upload(String fileName, InputStream input,String ftpPath) {
		FTPClient ftpClient = getFTPClient(localhost, port, ftpUserName, ftpPassword, ftpPath);
		try {
			// 切换到上传目录
			if (!ftpClient.changeWorkingDirectory(ftpPath)) {
				// 如果目录不存在创建目录
				String[] dirs = ftpPath.split("/");
				String tempPath = "";
				for (String dir : dirs) {
					if (null == dir || "".equals(dir)) {
						continue;
					}

					tempPath += "/" + dir;
					if (!ftpClient.changeWorkingDirectory(tempPath)) {
						ftpClient.makeDirectory(tempPath);
						ftpClient.changeWorkingDirectory(tempPath);
					}
				}
			}
			System.out.println(ftpPath);
			System.out.println(ftpClient.printWorkingDirectory());
			fileName=new String(fileName.getBytes("GBK"),"iso-8859-1");
			// 上传文件
			boolean b=ftpClient.storeFile(fileName, input);
			System.out.println(ftpClient.getReplyCode());
			return b;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (ftpClient != null) {
				try {
					ftpClient.logout();
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	 /** 
     *  
     * 

删除ftp上的文件

* @author tangw 2010-12-26 * @param srcFname * @return true || false */ public boolean removeFile(String srcFname,String ftpPath){ FTPClient ftpClient = getFTPClient(localhost, port, ftpUserName, ftpPassword, ftpPath); boolean flag = false; if( ftpClient!=null ){ try { flag = ftpClient.deleteFile(srcFname); } catch (IOException e) { e.printStackTrace(); }finally { if (ftpClient != null) { try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } return flag; } /** * * @param fileName * @param input */ public Boolean upload(String fileName, InputStream input ){ return upload(fileName,input,ftpPath); } /** * ftp下载 * * @param fileName * 要下载的文件名 * @param localPath * 保存本地路径 * */ public void download(String fileName, String localPath) { FTPClient ftpClient = getFTPClient(localhost, port, ftpUserName, ftpPassword, ftpPath); FileOutputStream fos = null; try { fos = new FileOutputStream(localPath); ftpClient.retrieveFile(fileName, fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (ftpClient != null) { try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } public String getLocalhost() { return localhost; } public void setLocalhost(String localhost) { this.localhost = localhost; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getFtpUserName() { return ftpUserName; } public void setFtpUserName(String ftpUserName) { this.ftpUserName = ftpUserName; } public String getFtpPassword() { return ftpPassword; } public void setFtpPassword(String ftpPassword) { this.ftpPassword = ftpPassword; } public String getFtpPath() { return ftpPath; } public void setFtpPath(String ftpPath) { this.ftpPath = ftpPath; } public String getLookPort() { return lookPort; } public void setLookPort(String lookPort) { this.lookPort = lookPort; } public String getFtpLookUrl() { return ftpLookUrl; } public void setFtpLookUrl(String ftpLookUrl) { this.ftpLookUrl = ftpLookUrl; } public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public String getProcessFilePath() { return processFilePath; } public void setProcessFilePath(String processFilePath) { this.processFilePath = processFilePath; } }

2、LayuiResponseData类(layui表格数据格式封装)

package com.ysm.util;

import java.util.List;

/**
 * layui表格数据格式
 * @author admin
 *
 */
public class LayuiResponseData {
	//响应码 数据总数
	private int code=0, count;
	//消息
	private String msg="";
	//数据
	List data;

	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public List getData() {
		return data;
	}
	public void setData(List data) {
		this.data = data;
	}
	
	public LayuiResponseData(int count,List data){
		this.count=count;
		this.data=data;
	}
	public LayuiResponseData() {
				
	}
}

3、LayuiUploadResponse(返回上传文件的字符串封装)

package com.ysm.util;
public class LayuiUploadResponse {

	String intactPath;
	String path;
	String fileName;
	
	public String getIntactPath() {
		return intactPath;
	}
	public void setIntactPath(String intactPath) {
		this.intactPath = intactPath;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}

5、Tools(开发常用的工具类用来验证数字之类)

package com.ysm.util;
/**
 * 开发常用工具类
 * @author admin
 *
 */
public class Tools {
	/**
	 * 
	 * @param value
	 * @return 如果字符串不为空或者长度不为零返回true
	 */
	public static boolean isNotNull( String value ) {
		if( value == null || "".equals( value.trim()) || "null".equalsIgnoreCase(value) ) {
			return false;
		}
		return true;
	}
	/**
	 * ISO编码转换成UTF8编码
	 * @param s
	 * @return
	 */
	public static String ISOtoUTF8(String s) { 
		try { 
			s = new String(s.getBytes("iso-8859-1"), "utf-8"); 
		} catch (Exception e) { 
		} 
		return s; 
	}
	/**
	 * 是否为num
	 * @param str
	 * @return boolean
	 */
	public static boolean isNum(String str){	
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");	
	}
}

新建一个Vo来接收查询数据

package com.ysm.vo;

import com.ysm.entity.User;

public class UserVo extends User{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String roleTypeName;

	private String sexName;
	
	private String loginTimeStr;
	
	private String userImageStr;


	public final String getUserImageStr() {
		return userImageStr;
	}

	public final void setUserImageStr(String userImageStr) {
		this.userImageStr = userImageStr;
	}

	public final String getLoginTimeStr() {
		return loginTimeStr;
	}

	public final void setLoginTimeStr(String loginTimeStr) {
		this.loginTimeStr = loginTimeStr;
	}

	public final String getSexName() {
		

		return sexName;
	}

	public final void setSexName(String sexName) {

		this.sexName = sexName;
	}

	public final String getRoleTypeName() {
		return roleTypeName;
	}

	public final void setRoleTypeName(String roleTypeName) {
		this.roleTypeName = roleTypeName;
	}
}

在user.xml里面的resultMap标签下添加以下


	
	
	
	
	
		insert into user(name,password,sex,loginTime,userImage,roleTypeId) 
		values(#{y.name},#{y.password},#{y.sex},#{y.loginTime},#{y.userImage},#{y.roleTypeId})
	
	
		
	
	
	
		update user set name=#{name},password=#{password},sex=#{sex},loginTime=#{loginTime},
			userImage=#{userImage},roleTypeId=#{roleTypeId}
		where id=#{id}
	
	
	

在UserMapper.java中添加配置文件中的方法(注意方法名称与上面查询标签里面的id一一对应)

	List selectUserTable(@Param("begin") Integer begin,@Param("page") Integer page,@Param("name") String name);
	List selectUserCount(@Param("name") String name);
	int insertUser(@Param("y") UserVo y);
	UserVo  selectUpdateUserById(@Param("id") Integer id);
	
	int updateUserById(UserVo userVo);
	
	User selectUserByName(@Param("name") String name);

在IUserService中添加以下抽象方法

		List selectUserTable(Integer begin,Integer page,String name);
		List selectUserCount(String name);
		boolean insertUser(UserVo y,MultipartFile file);
		UserVo  selectUpdateUserById(Integer id);
		int updateUserById(UserVo y,MultipartFile file);
		User selectUserByName(String name);

IUservice中的实现类

package com.ysm.service.impl;

import com.ysm.entity.User;
import com.ysm.mapper.UserMapper;
import com.ysm.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ysm.util.FTP_Upload_Download;
import com.ysm.util.Tools;
import com.ysm.vo.UserVo;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
 * 

* 服务实现类 *

* * @author admin * @since 2018-11-01 */ @Service public class UserServiceImpl extends ServiceImpl implements IUserService { @Autowired UserMapper userMapper; @Autowired FTP_Upload_Download upload; /** * 查询所有用户的数据 */ public List selectUserTable(Integer begin, Integer page, String name) { // TODO Auto-generated method stub List listUser=userMapper.selectUserTable(begin, page, name); for (Iterator iterator = listUser.iterator(); iterator.hasNext();) { UserVo userVo = (UserVo) iterator.next(); String imageUrl=upload.getFtpLookUrl()+userVo.getUserImage(); userVo.setUserImageStr(imageUrl); if (userVo.getSex()==0) { userVo.setSexName("男"); } else { userVo.setSexName("女"); } } return listUser; } /** * 查询用户的总行数 */ public List selectUserCount(String name) { // TODO Auto-generated method stub return userMapper.selectUserCount(name); } /** * 新增用户信息 */ public boolean insertUser(UserVo userVo,MultipartFile file) { // TODO Auto-generated method stub boolean returnValue=false; String path = upload.getUserFilePath(); String fileName =System.currentTimeMillis()+".jpg"; InputStream is = null; try { is = file.getInputStream(); //ftp是否上传成功 boolean b=upload.upload(fileName, is,path); if(!b){ return returnValue; } userVo.setUserImage(path+fileName); if (Tools.isNotNull(userVo.getName())&&Tools.isNotNull(userVo.getPassword()) &&Tools.isNotNull(userVo.getLoginTimeStr())&&userVo.getSex()!=null) { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); try { userVo.setLoginTime(format.parse(userVo.getLoginTimeStr())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i=userMapper.insertUser(userVo); if(i==0){ return returnValue; } else { returnValue=true; return returnValue; } } else { return returnValue; } } catch (IOException e) { e.printStackTrace(); return returnValue; } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 根据ID修改用户绑定操作 */ public UserVo selectUpdateUserById(Integer id) { // TODO Auto-generated method stub UserVo userVo=userMapper.selectUpdateUserById(id); StringBuilder imageUrl = new StringBuilder(); imageUrl.append(upload.getFtpLookUrl()+userVo.getUserImage()); userVo.setUserImageStr(imageUrl.toString()); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); userVo.setLoginTimeStr(sdf.format(userVo.getLoginTime())); return userVo; } /** * 修改保存操作 */ public int updateUserById(UserVo userVo, MultipartFile file) { // TODO Auto-generated method stub int returnUpdate=0; InputStream is = null; String userImageStrYan=userVo.getUserImage(); try { if (userImageStrYan!=null&&!userImageStrYan.equals("")) { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); try { userVo.setLoginTime(format.parse(userVo.getLoginTimeStr())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } returnUpdate=userMapper.updateUserById(userVo); } else { String path = upload.getUserFilePath(); String fileName =System.currentTimeMillis()+".jpg"; is = file.getInputStream(); //ftp是否上传成功 boolean b=upload.upload(fileName, is,path); //如果上传文件成功 if (b) { //删除以前的照片 Integer updateId=userVo.getId(); UserVo userVo2=userMapper.selectUpdateUserById(updateId); String ftpPath= upload.getUserFilePath(); String srcFname=userVo2.getUserImage(); //根据图片名称删除服务器上的照片 boolean ff= upload.removeFile(srcFname, ftpPath); userVo.setUserImage(path+fileName); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); try { userVo.setLoginTime(format.parse(userVo.getLoginTimeStr())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } returnUpdate=userMapper.updateUserById(userVo); } else { } } return returnUpdate; } catch (IOException e) { e.printStackTrace(); return returnUpdate; } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 登录方法 */ public User selectUserByName(String name) { // TODO Auto-generated method stub return userMapper.selectUserByName(name); } }

在src–》web包下UserController

package com.ysm.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.ysm.entity.Roletypetb;
import com.ysm.entity.User;
import com.ysm.service.IRoletypetbService;
import com.ysm.service.IUserService;
import com.ysm.util.FTP_Upload_Download;
import com.ysm.util.LayuiResponseData;
import com.ysm.vo.UserVo;

/**
 * 

* 前端控制器 *

* * @author * @since 2018-11-01 */ @Controller @RequestMapping("/user") public class UserController { @Autowired IUserService iUserService; @Autowired IRoletypetbService iRoletypetbService; @Autowired FTP_Upload_Download upload; //查询用户所有信息 @RequestMapping("selectUserTable") @ResponseBody public Object selectUserTable(String name,Integer page, Integer limit) { if(name==null||name.equals("")) { name=null; } if (page==null) { page=1; } if (limit==null) { limit=10; } int begin=(page-1)* limit; List userVosCount=iUserService.selectUserCount(name); int count=userVosCount.get(0).getId(); List listUser=iUserService.selectUserTable(begin, count, name); return new LayuiResponseData(count, listUser); } //弹出新增用户窗口 @RequestMapping("insertUser") @ResponseBody public ModelAndView insertUser(UserVo userVo) { ModelAndView userMv=new ModelAndView("insertUser"); List listRole=iRoletypetbService.selectList(null); userMv.addObject("listRole", listRole); return userMv; } //新增保存操作 //@RequestParam(required=false)MultipartFile file 表示图片接受可为空 @RequestMapping("insertUserSubmit") @ResponseBody public Object insertUserSubmit(UserVo userVo,@RequestParam(required=false)MultipartFile file) throws Exception { boolean returnValue=iUserService.insertUser(userVo, file); return returnValue; } //删除用户 @RequestMapping("deleteUserById") @ResponseBody public Object deleteUserById(Integer userId) { boolean returnValue=false; User user=iUserService.selectById(userId); String ftpPath= upload.getUserFilePath(); String srcFname=user.getUserImage(); //根据图片名称删除服务器上的照片 boolean ff= upload.removeFile(srcFname, ftpPath); if (ff) { returnValue=iUserService.deleteById(userId); } return returnValue; } //绑定修改数据 @RequestMapping("selectUpdateUserById") @ResponseBody public Object selectUpdateUserById(Integer userId) { ModelAndView updateUserView=new ModelAndView("updateUser"); UserVo userVo=iUserService.selectUpdateUserById(userId); List listRole=iRoletypetbService.selectList(null); updateUserView.addObject("listRole", listRole); updateUserView.addObject("updateUser", userVo); return updateUserView; } //修改数据提交 @RequestMapping("updateUserSubmit") @ResponseBody public Object updateUserSubmit(UserVo userVo,@RequestParam(required=false) MultipartFile file) throws Exception { int returnUpdate=iUserService.updateUserById(userVo, file); return returnUpdate; } //用户登录 @RequestMapping("login") @ResponseBody public Object login(String userName,String password) { ModelAndView MainMv=new ModelAndView("Main"); boolean returnValue=false; User user=iUserService.selectUserByName(userName); if (user!=null) { String dbpassword=user.getPassword(); if (dbpassword.equals(password)) { MainMv.addObject("user", user); return MainMv; } else { return returnValue; } } else { return returnValue; } } }

三、与页面交互

(1)新建jsp页面文件以及样式(如下图所示)
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第10张图片

1、PublicLink.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>








2、进入主页面 Main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>






测试模板


	
	
	
		


3、userMain.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>



用户管理




	
序号 用户名称 用户图片 性别 用户密码 登录时间 数据操作

4、新增数据的jsp页面(insertUser.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>



新增用户




	

5、修改用户数据的jsp页面(updateUser.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/jsp/PublicLink/PublicLink.jsp"%>



修改用户





	
checked value="0" title="男" > checked value="1" title="女" >

web里面的文件都是一些layui前端框架的文件,可以自己下载
下载网址:https://www.layui.com/(打开之后点击立即下载按钮即可)
另外还需要引用一个js文件(jquery-3.3.1.min.js)
下载网址:http://down.chinaz.com/soft/30789.htm
java实现将文件上传到本地的ftp服务器中(layui前端框架form表单数据与图片一起提交)_第11张图片

你可能感兴趣的:(程序人生)