java:nginx(java代码操作ftp服务器)
1、检查是否安装了vsftpd
[root@linux01 ~]# rpm -qa|grep vsftpd
2、安装vsftpd
[root@linux01 ~]# yum -y install vsftpd
3、启动vsftpd
[root@linux01 ~]# service vsftpd start
4、设置开机启动
[root@linux01 ~]# chkconfig vsftpd on
5、管理vsftpd相关命令
启动vsftpd: service vsftpd start
停止vsftpd: service vsftpd stop
重启vsftpd: service vsftpd restart
状态vsftpd: service vsftpd status
6.nginx启动
[root@linux01 conf]# cd /usr/local/nginx-1.8.1/sbin
[root@linux01 sbin]# ./nginx -s reload
1.ftp_demo Maven Webapp:
UploadController.java:
package com.ftp.demo.controller; import java.util.HashMap;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import com.ftp.demo.model.User;
import com.ftp.demo.service.UploadService; @Controller
public class UploadController { @Autowired
private UploadService fileUploadService; /**
* @description 跳转到头像上传页面
* @return
*/
@RequestMapping("/")
public String turnUploadPage() {
return "file_upload";
} /**
* @description 跳转到头像上传页面2
* @return
*/
@RequestMapping("/ajax")
public String turnUploadPageAjax() {
return "file_upload_ajax";
} @RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Object upload(@RequestParam("headPic") MultipartFile[] files) {
String[] picsPath = new String[files.length];
User user = new User(1L, "zhangsan", "123456", null);
Map<String, Object> resultMap = new HashMap<String, Object>();
if (files.length <= 0) {
return "error";
}
for(int i = 0; i < files.length; i++) {
// 直接调用service
try {
resultMap = fileUploadService.upload(files[i]);
picsPath[i] = (String)resultMap.get("ftpPicPath"); } catch (Exception e) {
e.printStackTrace();
}
} String ftpPicPath = (String) resultMap.get("ftpPicPath");
if (ftpPicPath != null) {// 上传文件成功
// 1.通过登录进来的用户(通过存入session的用户信息获取到用户的id)
Long userId = user.getId();
// 2.通过用户的id查询该用户信息
if (userId == user.getId()) {
// 3.把头像的路径更新进查询出的用户信息
// setHeadPicPath是什么?-->ftp服务器上的图片所在路径-->从service中传入controller
user.setHeadPicPath(ftpPicPath);
}
// 4.判断是否更新成功
if (null != user.getHeadPicPath() && !"".equals(user.getHeadPicPath())) {
System.out.println(user);
// 更新成功
}
// model.addAttribute("user", user);
return picsPath;
}
return "error";
} }
User.java:
package com.ftp.demo.model; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -3925195892141429182L; private Long id;
private String username;
private String password;
private String headPicPath; public User() { } public User(Long id, String username, String password, String headPicPath) {
this.id = id;
this.username = username;
this.password = password;
this.headPicPath = headPicPath;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getHeadPicPath() {
return headPicPath;
} public void setHeadPicPath(String headPicPath) {
this.headPicPath = headPicPath;
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((headPicPath == null) ? 0 : headPicPath.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (headPicPath == null) {
if (other.headPicPath != null)
return false;
} else if (!headPicPath.equals(other.headPicPath))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
} @Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", headPicPath=" + headPicPath
+ "]";
} }
UploadService.java:
package com.ftp.demo.service; import java.util.HashMap;
import java.util.Map; import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile; import com.ftp.demo.utils.FtpUtil;
import com.ftp.demo.utils.IDUtil;
public class UploadService { private String ftpIp;
private String ftpPort;
private String ftpUsername;
private String ftpPassword;
private String ftpBasePaht;// /home/ftp/www
private String httpBasePath; public String getFtpIp() {
return ftpIp;
} public void setFtpIp(String ftpIp) {
this.ftpIp = ftpIp;
} public String getFtpPort() {
return ftpPort;
} public void setFtpPort(String ftpPort) {
this.ftpPort = ftpPort;
} 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 getFtpBasePaht() {
return ftpBasePaht;
} public void setFtpBasePaht(String ftpBasePaht) {
this.ftpBasePaht = ftpBasePaht;
} public String getHttpBasePath() {
return httpBasePath;
} public void setHttpBasePath(String httpBasePath) {
this.httpBasePath = httpBasePath;
} /**
* @description 文件上传
* @param file
* @return
*/
public Map<String, Object> upload(MultipartFile file) {
Map<String, Object> resultMap = new HashMap<String, Object>();
if(file == null) {
return null;
}
// 1. 获取该文件的文件名(从页面传递过来的名字)
String oldFileName = file.getOriginalFilename();
// 2.创建新的名字(防止不同用户上传的图片名字一致,导致图片被覆盖)
String newFileName = IDUtil.genImageName();
// 3.新生成的图片名字拼接成图片的类型
// 4636437326167.jpg
newFileName = newFileName + oldFileName.substring(oldFileName.lastIndexOf("."));
// 4.2017/09/27生成用户需要存放的路径,路径以当天的日期为文件夹
String filePath = new DateTime().toString("yyyy/MM/dd");
// 5.开始ftp的上传准备
try {
Map<String, Object> map = FtpUtil.uploadFile(ftpIp, Integer.parseInt(ftpPort), ftpUsername, ftpPassword, ftpBasePaht, filePath,
newFileName, file.getInputStream());
String picPath = (String)map.get("picPaht");
String ftpPicPath = "";
if(picPath != null && (boolean)map.get("result") == true) {
ftpPicPath = httpBasePath+picPath+"/"+newFileName;
resultMap.put("ftpPicPath", ftpPicPath);
}
} catch (Exception e) {
e.printStackTrace();
} return resultMap;
} }
FtpUtil.java:
package com.ftp.demo.utils; import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply; public class FtpUtil { /**
* Description: 向FTP服务器上传文件
*
* @author Seven Lee
*
* @param host
* FTP服务器hostname:IP
* @param port
* FTP服务器端口
* @param username
* FTP登录账号
* @param password
* FTP登录密码
* @param basePath
* FTP服务器基础目录
* @param filePath
* FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* /home/ftp/www/2017/04/06/1.txt
* @param filename
* 上传到FTP服务器上的文件名
* @param input
* 输入流
* @return 成功返回true,否则返回false
* @throws Exception
*/
public static Map<String, Object> uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) throws Exception {
String picPath = "";
String tempPath = "";
Map<String, Object> resultMap = new HashMap<String, Object>();
boolean result = false;
// 1.创建FTP客户端对象
FTPClient ftp = new FTPClient();
try {
int reply;
// 2.通过ip和端口号进行连接ftp服务器
ftp.connect(host, port);
// 3.通过账号和密码进行登录
ftp.login(username, password);// 返回boolean类型,成功true,失败false
// getReplyCode:拿到登录后响应吗(决定了是否登录成功,并且根据响应码可以得到登录失败的具体原因)
reply = ftp.getReplyCode();
// ftp.getReplyCode()-->230说明登录成功-->如果返回的是530表示密码错误
// isPositiveCompletion(reply):检测得到的响应码是否标识了该用户登录的状态,返回true/false
if (!FTPReply.isPositiveCompletion(reply)) {
// 标识登录失败,退出ftp服务器
ftp.disconnect();
resultMap.put("result", result);
resultMap.put("picPaht", null);
return resultMap;// false-->说明登录失败
}
//basePath:/home/ftp/www+/2017/09/27
// changeWorkingDirectory判断目标上传的目录知否存在,返回true/false
if (!ftp.changeWorkingDirectory(basePath + filePath)) {// /2017/09/27-->["","2017","09","27"]
// 该目录不存在
// filePath.split("/");-->2017, 09, 27
String[] dirs = filePath.split("/");
// /home/ftp/www
tempPath = basePath;
// 增强for循环开始循环,是要为下面创建文件夹做准备
for (String dir : dirs) {
// 第一次循环:dir:可能是2017也可能为""
// 如果第一次循环,拿到的数据为"",那么第二次循环进来一定拿到2017
if (null == dir || "".equals(dir))
continue;// 跳出该次循环,进入下一次循环
// tempPath:/home/ftp/www/2017
tempPath += "/" + dir;
picPath += "/"+dir;
// 调用changeWorkingDirectory(tempPath)再次判断该文件夹是否存在
if (!ftp.changeWorkingDirectory(tempPath)) {
// 如果不存在
// 调用makeDirectory(tempPath)-->创建文件夹 mkdir 返回true/fase-->如果创建文件夹失败,意味着上传失败
if (!ftp.makeDirectory(tempPath)) {
resultMap.put("result", result);
resultMap.put("picPaht", null);
return resultMap;
} else {
// 如果创建文件夹成功,再次验证该目录是否存在
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
// 设置该上传的文件转换类型(字节流)
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// 这里开始真正重点!!!开始上传
// filename:从uploadService中传递来的新生成的文件名,返回true/false
if (!ftp.storeFile(filename, input)) {
// 如果上传失败,返回false
resultMap.put("result", result);
resultMap.put("picPaht", null);
return resultMap;
}
input.close();
// 退出
ftp.logout();
// 确保了一定是上传成功的
result = true;
} catch (IOException e) {
e.printStackTrace();
throw new Exception(e);
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
resultMap.put("result", result);
resultMap.put("picPaht", picPath);
return resultMap;
} }
IDUtil.java:
package com.ftp.demo.utils; import java.util.Random; /**
* 各种id生成策略
*
* @version 1.0
*/
public class IDUtil { /**
* 图片名生成
*/ public static String genImageName() {
// 获取到当前时间的毫秒数647238647823647867836287181767867
long millis = System.currentTimeMillis();
Random random = new Random();
// 随机出1-3位的随机数
int end3 = random.nextInt(999);
// millis:当前时间毫秒数+
// %03d占位符:%占位符,d:数字,03:需要占用3位,如果不够三位在前面补0
String str = millis + String.format("%03d", end3);
// str:当前时间的毫秒数+随机出的数字
// 为了防止图片名重复,导致图片被覆盖 return str;
} }
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- mybatis默认是没有开启延迟加载的 需要手动开启 -->
<settings>
<!-- 延迟加载 默认false -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 积极加载 默认true -->
<setting name="aggressiveLazyLoading" value="false" />
<!--开启缓存 -->
<setting name="cacheEnabled" value="true" />
</settings>
</configuration>
applicationContext-db.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!--数据源配置 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="filters" value="stat" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件,**表示迭代查找 -->
<property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" />
<!--mybatis配置文件位置 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
</bean>
</beans>
applicationContext-tx.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 事务详情 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="select*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!--支持基于注解的aspectj -->
<aop:aspectj-autoproxy /> <!--aop编程,切入点表达式 确定增强的连接器,从而获得切入点 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ftp.demo.service..*.*(..)))" />
</aop:config>
</beans>
applicationContext-upload.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="fileUploadService" class="com.ftp.demo.service.UploadService">
<property name="ftpIp" value="${ftp.host}"></property>
<property name="ftpPort" value="${ftp.port}"></property>
<property name="ftpUsername" value="${ftp.username}"></property>
<property name="ftpPassword" value="${ftp.password}"></property>
<property name="ftpBasePaht" value="${ftp.base.path}"></property>
<property name="httpBasePath" value="${http.base.url}"></property>
</bean>
</beans>
applicationContext-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 自动扫描且只扫描@Controller
其实@autoWired标识的自动注入service已经注入进来了
只会扫描controller注解,并不会去扫描配置文件中配置的<bean id="fileUploadService">
到底谁谁该扫描呢?-@autoWired去扫描service的时候,就不知道该谁来操作service
只能扫描到@service,并不能扫描到配置文件-通过配置文件的自动加载把fileUploadService注入进来,
但是开始调用的时候,扫描开始冲突,spring要等待springmvc来处理service,但是springmvc得到通知spring已经扫描了service,就
开始等待spring来处理这个service
-->
<context:component-scan base-package="com.ftp.demo.controller" /> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
<mvc:default-servlet-handler /> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" value="UTF-8" />
</bean>
<!-- 格式化json -->
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prettyPrint" value="true" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven> <!-- Jsp视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean> <!--文件上传视图解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--允许上传的文件最大大小 单位是byte 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize" value="5242880" />
</bean> <!-- 开启aop对类代理 -->
<aop:config proxy-target-class="true" /> </beans>
application.properties:
#mysql connector
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shiro
jdbc.username=root
jdbc.password=root #ftp connector
ftp.host=192.168.1.165
ftp.port=21
ftp.username=ftpuser
ftp.password=123456
ftp.base.path=/home/ftp/www
http.base.url=http\://192.168.1.165
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!--加载配置文件 -->
<context:property-placeholder location="classpath:application.properties" /> <!-- 扫描的包路径 去掉mvc的注解
不但扫描到了service也一并扫描了其他的注解形式
排除controller的注解,只扫描service
-->
<context:component-scan base-package="com.ftp.demo.service" /> <!-- 数据源配置 -->
<import resource="spring/applicationContext-db.xml" />
<!-- 事务配置 -->
<import resource="spring/applicationContext-tx.xml" />
<!-- 文件上传组件 -->
<import resource="spring/applicationContext-upload.xml" />
</beans>
file_upload_ajax.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'file_upload_ajax.jsp' starting page</title>
<script type="text/javascript" src="/ftp_demo/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
/**
使用ajax进行文件的上传
首先要注意data的参数
data需要把整个form表单一并传递给后台,让后台的java代码认识enctype="multipart/form-data"
*/
$(function(){ $("#add_pic").click(function(){
$("#add_pic_implements").prepend("<input type='file' name='headPic'/>");
}); $("#add").click(function(){
$.ajax({
url:"/ftp_demo/upload",
type:"post",
data: new FormData($('#upload_form')[0]),
processData: false,
contentType: false,// 是指定浏览器向服务器传递数据的编码集-->默认支持application/x-www-form-urlencoded
// contentType不指定为false,会造成contentType指定编码机混乱,但是如果指定了contentType: false的情况下
// 会直接选择使用form表单的编码集,自己的编码集失效
success: function(data){
$("#show_pic").show();
for(var i = 0; i < data.length; i++) {
$("#show_pic").append("<img src="+data[i]+" />");
}
}
});
});
}); </script> </head> <body>
<!--
processData为true
会自动把enctype="multipart/form-data"转换为默认的enctype="application/x-www-form-urlencoded"
enctype="application/x-www-form-urlencoded":只支持对象,简单的类型或者封装类型,并不支持上传的类型,也就是multipart/form-data -->
<form id="upload_form" enctype="multipart/form-data" method="post">
请上传头像:
<div id="add_pic_implements">
<input type="file" name="headPic"/>
</div>
<input id="add" type="button" value="upload" />
</form> <div>
<input id="add_pic" type="button" value="添加图片" />
</div> <div id="show_pic" style="display:none;">
<h4>上传成功</h4>
</div> </body>
</html>
file_upload.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'file_upload.jsp' starting page</title> </head> <body> <form action="/ftp_demo/upload" method="post" enctype="multipart/form-data">
头像:<input type="file" name="headPic" />
<input type="submit" value="upload">
</form> </body>
</html>
success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> </head> <body> <h1>图片的回显</h1>
<h4>上传的图片为:</h4>
<img alt="图片无法展示" src="${user.headPicPath }">
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> <!--Spring入口文件的配置-->
<!-- 确定配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置spring 监听器,加载xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 解决POST请求的中文乱码-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- DispatcherServlet:前端控制器 配置前端控制器servlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载前端控制器配置文件 上下文配置位置-->
<init-param>
<!--contextConfigLocation:指定springmvc配置的加载位置,
如果不指定则默认加 载WEB-INF/[DispatcherServlet的Servlet名字]-servlet.xml(例如springmvc-servlet.xml)。
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc/applicationContext-mvc.xml</param-value>
</init-param>
<!-- 表示随WEB服务器启动 -->
<load-on-startup>1</load-on-startup>
</servlet> <!-- 可以拦截二种请求
第一种:拦截固定后缀的url,比如设置为 *.do、*.action,
例如:/user/add.action 此方法最简单,不会导致静态资源(jpg,js,css)被拦截
第二种:拦截所有 设置为/,
例如:/user/add /user/add.action此方法可以实现REST风格的url
很多互联网类型的应用使用这种方式.但是此方法会导致静态文件(jpg,js,css)被拦截后不能正常显示.需要特殊处理
错误设置:拦截所有,设置为/*,此设置方法错误,因为请求到Action, 当action转到jsp时再次被拦截,提示不能根据jsp路径mapping成功.
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.upload.demo</groupId>
<artifactId>ftp_demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ftp_demo Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<!-- junit -->
<junit.version>4.12</junit.version>
<!-- spring -->
<spring.version>4.3.4.RELEASE</spring.version>
<!-- json -->
<jackson.version>2.8.1</jackson.version>
<fastjson.version>1.2.17</fastjson.version> <!-- servlet, jsp, jstl -->
<servlet-api.version>3.0.1</servlet-api.version>
<jsp-api.version>2.0</jsp-api.version>
<jstl.version>1.2</jstl.version> <!-- mysql -->
<mysql.version>5.1.40</mysql.version>
<druid.version>1.0.26</druid.version> <!-- mybatis -->
<mybatis.version>3.3.0</mybatis.version>
<mybatis.spring.version>1.2.3</mybatis.spring.version>
<mybatis.mapper.version>3.3.9</mybatis.mapper.version> <!-- slf4j -->
<slf4j.version>1.7.7</slf4j.version> <!-- file upload -->
<commons-fileupload.version>1.3.1</commons-fileupload.version> <!-- httpClient -->
<httpclient.version>4.3.5</httpclient.version> <!-- commons-net(ftp) -->
<commons-net.version>3.5</commons-net.version> <!-- joda time -->
<joda-time.version>2.9.4</joda-time.version>
</properties> <dependencies> <!-- joda time begin -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<!-- joda time end --> <!--spring start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring end --> <!--json start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--json end --> <!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency> <!-- jsp -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency> <!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency> <!-- database begin -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- database end --> <!-- slf4j begin -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- slf4j end --> <!-- mybatis common mapper plugin -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${mybatis.mapper.version}</version>
</dependency> <!-- file upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!-- file upload --> <!-- httpclient begin -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<!-- httpclient end --> <!-- ftp begin -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<!-- ftp end --> </dependencies>
<build>
<finalName>ftp_demo</finalName>
</build>
</project>
java:nginx(java代码操作ftp服务器)的更多相关文章
- java 上传文件到 ftp 服务器
1. java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...
- java代码实现ftp服务器的文件上传和下载
java代码实现文件上传到ftp服务器: 1:ftp服务器安装: 2:ftp服务器的配置: 启动成功: 2:客户端:代码实现文件的上传与下载: 1:依赖jar包: 2:sftpTools 工具类: ...
- JAVA中通过代码操作PC内容进行功能的实现
1.添加计划任务,用户项目中需要添加定时提醒功能: 计划任务只需要写一个继承java.util.TimerTask的类,覆盖其中的run方法即可,例如: import java.util.*; p ...
- Java上传文件FTP服务器代码
1. 在实际的应用重,通常是通过程序来进行文件的上传. 2. 实现java上传文件到ftp服务器中 新建maven项目 添加依赖 <dependency> <groupId>c ...
- 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等
记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...
- PHP操作FTP类 (上传下载移动创建等)
使用PHP操作FTP-用法 Php代码 收藏代码 <? // 联接FTP服务器 $conn = ftp_connect(ftp.server.com); // 使用username和passwo ...
- Python一秒搭建ftp服务器,帮助你在局域网共享文件【华为云技术分享】
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/devcloud/article/detai ...
- Python一秒搭建ftp服务器,帮助你在局域网共享文件
"老板 来碗面" "要啥面?" "内牛满面.." 最近项目上的事情弄得人心累,本来是帮着兄弟项目写套入口代码,搞着搞着就被拉着入坑了.搞开发 ...
- Web浏览器导出FTP服务器上的文件
开发思路:1.代码登录ftp服务器下载文件到服务器2.通过web浏览器下载服务器上的文件 using System; using System.Collections; using System.Co ...
随机推荐
- myBatis整合Spring理论
整合目标 更少的编码 更少的配置 足够的灵活性 1.更少的编码 只写接口,不写实现(myBatis帮我们实现接口) 2-1.更少的配置-别名 在java的规范当中,表示一个类型是通过包名+类名,但是整 ...
- JVM的四种GC算法
程序在运行过程中,会产生大量的内存垃圾(一些没有引用指向的内存对象都属于内存垃圾,因为这些对象已经无法访问,程序用不了它们了,对程序而言它们已经死亡),为了确保程序运行时的性能,java虚拟机在程序运 ...
- pycharm中如何让两个项目并存
之前总是打开一个,另外一个没有了,来回切换还要找最近的project.十分麻烦. 1.File下拉项中选择Settings 2.Settings设置界面打开Project下拉列表,选择“Project ...
- 前端每周清单第 49 期:Webpack 4 Beta 尝鲜,React Windowing 与 setState 分析,Web Worker 实战
前端每周清单专注前端领域内容,以对外文资料的搜集为主,帮助开发者了解一周前端热点:分为新闻热点.开发教程.工程实践.深度阅读.开源项目.巅峰人生等栏目.欢迎关注[前端之巅]微信公众号(ID: fron ...
- 浅析flex 布局
Flex基本概念: 容器默认存在两根轴:水平的主轴(main axis)和垂直的交叉轴(cross axis).主轴的开始位置(与边框的交叉点)叫做main start,结束位置叫做main end: ...
- eclipse打开项目中文件时左侧project explorer同时展开该文件的路径
如图,点击Package Explorer面板上的双向箭头图标即可
- less命令:查看文件内容
less 命令的作用和 more 十分类似,都用来浏览文本文件中的内容,不同之处在于,使用 more 命令浏览文件内容时,只能不断向后翻看,而使用 less 命令浏览,既可以向后翻看,也可以向前翻看. ...
- vue 钩子函数的使用
1.什么是自定义指令,有哪些钩子函数及自定义指令的使用场景 ①自定义指令是什么?以及自定义指令的使用场景 在Vue中,有很多内置指令,但是这些指令只能满足我们最基础的使用,当我们在实际项目中遇到了必须 ...
- ZAP-Queries【luogu3455】
题目大意 有不超过\(50000\)个询问,每次询问有多少正整数对\(x\),\(y\),满足\(x\leqslant a\),\(y \leqslant b\),并且\(gcd(x,y)=c\).其 ...
- Codeforces Gym 101630J Travelling from Petersburg to Moscow (最短路)
题目链接 http://codeforces.com/gym/101630/attachments 题解 zyb学长的题. 先枚举第\(k\)大的边权,设其边权为\(x\),然后把每条边边权减掉\(x ...