一、引入POM依赖
<?xml version="1.0" encoding="UTF-8"?>
< 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/xsd/maven-4.0.0.xsd" >
< modelVersion> 4.0.0</ modelVersion>
< groupId> com.wang</ groupId>
< artifactId> SpringDemo</ artifactId>
< version> 1.0-SNAPSHOT</ version>
< packaging> war</ packaging>
< properties>
< project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding>
< spring.version> 4.3.8.RELEASE</ spring.version>
< commons-fileupload.version> 1.3.1</ commons-fileupload.version>
</ properties>
< dependencies>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-core</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-aop</ 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>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-jdbc</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-tx</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 6.0.6</ version>
</ dependency>
< dependency>
< groupId> org.csource.fastdfs</ groupId>
< artifactId> fastdfs</ artifactId>
< version> 1.2</ version>
</ dependency>
< dependency>
< groupId> commons-fileupload</ groupId>
< artifactId> commons-fileupload</ artifactId>
< version> ${commons-fileupload.version}</ version>
</ dependency>
< dependency>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
< version> 4.11</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.slf4j</ groupId>
< artifactId> slf4j-log4j12</ artifactId>
< version> 1.7.2</ version>
</ dependency>
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> fastjson</ artifactId>
< version> 1.2.36</ version>
</ dependency>
< dependency>
< groupId> org.projectlombok</ groupId>
< artifactId> lombok</ artifactId>
< version> 1.16.12</ version>
< scope> provided</ scope>
</ dependency>
</ dependencies>
< build>
< plugins>
< plugin>
< groupId> org.apache.maven.plugins</ groupId>
< artifactId> maven-compiler-plugin</ artifactId>
< version> 3.1</ version>
< configuration>
< source> 1.8</ source>
< target> 1.8</ target>
< encoding> UTF-8</ encoding>
< showWarnings> true</ showWarnings>
</ configuration>
</ plugin>
< plugin>
< groupId> org.apache.tomcat.maven</ groupId>
< artifactId> tomcat7-maven-plugin</ artifactId>
< version> 2.2</ version>
< configuration>
< port> 8080</ port>
< path> /</ path>
< uriEncoding> UTF-8</ uriEncoding>
< server> tomcat7</ server>
</ configuration>
</ plugin>
</ plugins>
</ build>
</ project>
二、配置Web.xml
<?xml version="1.0" encoding="UTF-8"?>
< web-app xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xmlns = " http://java.sun.com/xml/ns/javaee"
xsi: schemaLocation= " http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = " WebApp_ID" version = " 3.0" >
< servlet>
< servlet-name> dispatcherServlet</ servlet-name>
< servlet-class> org.springframework.web.servlet.DispatcherServlet</ servlet-class>
< init-param>
< param-name> contextConfigLocation</ param-name>
< param-value> classpath:application-mvc.xml</ param-value>
</ init-param>
</ servlet>
< servlet-mapping>
< servlet-name> dispatcherServlet</ servlet-name>
< url-pattern> /</ url-pattern>
</ servlet-mapping>
< 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>
< welcome-file-list>
< welcome-file> /WEB-INF/jsp/index.jsp</ welcome-file>
</ welcome-file-list>
</ web-app>
三、applicationContext-SpringMVC.xml配置
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: p= " http://www.springframework.org/schema/p"
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"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" >
< context: property-placeholder location = " classpath*:*.properties" />
< context: annotation-config/>
< mvc: annotation-driven>
< mvc: message-converters register-defaults = " true" >
< bean class = " com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter" >
< property name = " supportedMediaTypes" value = " application/json" />
< property name = " features" >
< array>
< value> WriteMapNullValue</ value>
< value> WriteDateUseDateFormat</ value>
</ array>
</ property>
</ bean>
</ mvc: message-converters>
</ mvc: annotation-driven>
< mvc: default-servlet-handler/>
< mvc: resources mapping = " /static/**" location = " /WEB-INF/static/" />
< bean id = " multipartResolver"
class = " org.springframework.web.multipart.commons.CommonsMultipartResolver" >
< property name = " defaultEncoding" value = " UTF-8" > </ property>
< property name = " maxUploadSize" value = " 5242880" > </ property>
</ bean>
< bean id = " viewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver"
p: prefix= " /WEB-INF/jsp/" p: suffix= " .jsp" />
< context: component-scan base-package = " com.wang.controller" />
</ beans>
四 、application.properties配置(配置文件服务器ip)
FILE_SERVER_URL= 192.168 .100 .21 /
五、fdfs_client.conf文件配置(FastDFS核心配置)
# connect timeout in seconds
# default value is 30 s
connect_timeout= 30
# network timeout in seconds
# default value is 30 s
network_timeout= 60
# the base path to store log files
base_path= / home/ fastdfs
# tracker_server can ocur more than once, and tracker_server format is
# "host:port" , host can be hostname or ip address
# 配置自己的服务器地址和端口
tracker_server= 192.168 .100 .21 : 22122
#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level= info
# if use connection pool
# default value is false
# since V4. 05
use_connection_pool = false
# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4. 05
connection_pool_max_idle_time = 3600
# if load FastDFS parameters from tracker server
# since V4. 05
# default value is false
load_fdfs_parameters_from_tracker= false
# if use storage ID instead of IP address
# same as tracker. conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4. 05
use_storage_id = false
# specify storage ids filename, can use relative or absolute path
# same as tracker. conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4. 05
storage_ids_filename = storage_ids. conf
#HTTP settings
http. tracker_server_port= 80
#use "#include" directive to include HTTP other settiongs
##include http. conf
六、日志的配置文件
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j. rootCategory= INFO, CONSOLE debug info warn error fatal
log4j. rootCategory= debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j. logger. org. apache. axis. enterprise= FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j. appender. CONSOLE= org. apache. log4j. ConsoleAppender
log4j. appender. CONSOLE. layout= org. apache. log4j. PatternLayout
log4j. appender. CONSOLE. layout. ConversionPattern= % d{ ISO8601} % - 6 r [ % 15.15 t] % - 5 p % 30.30 c % x - % m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j. appender. LOGFILE= org. apache. log4j. FileAppender
log4j. appender. LOGFILE. File= d: axis. log
log4j. appender. LOGFILE. Append= true
log4j. appender. LOGFILE. layout= org. apache. log4j. PatternLayout
log4j. appender. LOGFILE. layout. ConversionPattern= % d{ ISO8601} % - 6 r [ % 15.15 t] % - 5 p % 30.30 c % x - % m\n
七、创建文件上传的工具类
package com. wang. common;
import org. csource. common. NameValuePair;
import org. csource. fastdfs. *;
import java. io. BufferedOutputStream;
import java. io. IOException;
public class FastDFSClient {
private TrackerClient trackerClient = null;
private TrackerServer trackerServer = null;
private StorageServer storageServer = null;
private StorageClient1 storageClient = null;
public FastDFSClient ( String conf) throws Exception {
if ( conf. contains ( "classpath:" ) ) {
conf = conf. replace ( "classpath:" , this . getClass ( ) . getResource ( "/" ) . getPath ( ) ) ;
}
ClientGlobal. init ( conf) ;
trackerClient = new TrackerClient ( ) ;
trackerServer = trackerClient. getConnection ( ) ;
storageServer = null;
storageClient = new StorageClient1 ( trackerServer, storageServer) ;
}
public String uploadFile ( String fileName, String extName, NameValuePair[ ] metas) throws Exception {
return storageClient. upload_file1 ( fileName, extName, metas) ;
}
public String uploadFile ( String fileName) throws Exception {
return uploadFile ( fileName, null, null) ;
}
public String uploadFile ( String fileName, String extName) throws Exception {
return uploadFile ( fileName, extName, null) ;
}
public String uploadFile ( byte [ ] fileContent, String extName, NameValuePair[ ] metas) throws Exception {
return storageClient. upload_file1 ( fileContent, extName, metas) ;
}
public String uploadFile ( byte [ ] fileContent) throws Exception {
return uploadFile ( fileContent, null, null) ;
}
public String uploadFile ( byte [ ] fileContent, String extName) throws Exception {
return uploadFile ( fileContent, extName, null) ;
}
public int download_file ( String path, BufferedOutputStream output) {
int result = - 1 ;
try {
byte [ ] b = storageClient. download_file1 ( path) ;
try {
if ( b != null) {
output. write ( b) ;
result = 0 ;
}
} catch ( Exception e) {
}
finally {
if ( output != null) {
try {
output. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
return result;
}
public byte [ ] download_bytes ( String path) {
byte [ ] b = null;
try {
b = storageClient. download_file1 ( path) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
return b;
}
public Integer delete_file ( String group, String storagePath) {
int result = - 1 ;
try {
result = storageClient. delete_file ( group, storagePath) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
return result;
}
public Integer delete_file ( String storagePath) {
int result = - 1 ;
try {
result = storageClient. delete_file1 ( storagePath) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
return result;
}
public FileInfo getFile ( String groupName, String remoteFileName) {
try {
return storageClient. get_file_info ( groupName, remoteFileName) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
return null;
}
}
八、创建文件上传得Controller
package com. wang. controller;
import com. wang. common. FastDFSClient;
import com. wang. user. User;
import org. springframework. beans. factory. annotation. Value;
import org. springframework. stereotype. Controller;
import org. springframework. web. bind. annotation. RequestMapping;
import org. springframework. web. bind. annotation. ResponseBody;
import org. springframework. web. multipart. MultipartFile;
@Controller
public class SpringController {
@Value ( "${FILE_SERVER_URL}" )
private String FILE_SERVER_URL;
@RequestMapping ( "/hello" )
public String springDemo ( ) {
return "hello" ;
}
@RequestMapping ( "/upload" )
@ResponseBody
public String upload ( MultipartFile file) {
String URL = "上传失败" ;
String path = file. getOriginalFilename ( ) ;
String extName = path. substring ( path. lastIndexOf ( "." ) + 1 ) ;
try {
FastDFSClient client = new FastDFSClient ( "classpath:fdfs_client.conf" ) ;
String filePath = client. uploadFile ( file. getBytes ( ) , extName) ;
URL = FILE_SERVER_URL + filePath;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
return URL;
}
@RequestMapping ( "/user" )
@ResponseBody
public User getUser ( ) {
return new User ( ) . setUserName ( "xian" ) . setPassWord ( "xian" ) ;
}
@RequestMapping ( "/postUser" )
@ResponseBody
public User postUser ( User user) {
return user;
}
}
九、创建上传得JSP页面(此处简单测试)
< % @ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" % >
< ! DOCTYPE HTML>
< html>
< head>
< meta http- equiv= "Content-Type" content= "text/html; charset=UTF-8" >
< title> 单图片上传< / title>
< / head>
< body>
< fieldset>
< legend> 图片上传< / legend>
< h2> 只能上传单张10 M以下的 PNG、JPG、GIF 格式的图片< / h2>
< form action= "/upload" method= "post" enctype= "multipart/form-data" >
选择文件: < input type= "file" name= "file" >
< input type= "submit" value= "上传" >
< / form>
< / fieldset>
< / body>
< / html>
十、通过浏览器访问FastDFS返回的地址即可看到我们上传到服务器上的文件,当然这个文件不局限于图片。