第七章:文件上传-4. 使用图片服务器

在微架构的系统之中,若是要保存上传图片内容,确定要保存在图片服务器之中,由于若是你直接保存在web项目里面,那么该图片只有一个web容器能够看见,而且在集群之中容器之间的数据也无法进行共享,那么久须要有一个图片服务器,本次使用fastdfs的图片服务器完成总体的图片保存。javascript

1.若是要想使用图片服务器,则首先必定要进行一些依赖包的配置,修改pom.xml配置文件,追加fastdfs依赖支持包:html

<dependency>
			<groupId>com.github.kischang</groupId>
			<artifactId>fastdfs-client</artifactId>
			<version>0.1</version>
		</dependency>

完整pomjava

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.mldn</groupId>
		<artifactId>microboot</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>microboot-upload</artifactId>
	<name>microboot-upload</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>com.github.kischang</groupId>
			<artifactId>fastdfs-client</artifactId>
			<version>0.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>

	</dependencies>
</project>

2.随后因为该图片服务器有token认证处理过程,因此必定要保证有认证的配置文件,在"src/main/resources"目录之中建立"fastdfs_client.conf"文件git

# 配置上你tracker的链接地址
tracker_server=fastdfs-tracker:22122
# 表示如今要进行token检测
http.anti_steal_token=true
# 进行认证的密码处理
http.secret_key=mldnhelloworldhahheihanhheiehinajueduicaibudao

3.修改控制器中的上传处理操做github

microboot/pom.xmlweb

<includes>
					<include>**/*.properties</include>
					<include>**/*.yml</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
					<include>**/*.p12</include>
					<include>**/*.conf</include>
				</includes>

完整pomspring

<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>cn.mldn</groupId>
	<artifactId>microboot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<name>microboot</name>
	<url>http://maven.apache.org</url>
	<properties>
		<jdk.version>1.8</jdk.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>1.5.4.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<build>
		<finalName>microboot</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.yml</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
					<include>**/*.p12</include>
					<include>**/*.conf</include>
				</includes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
				</includes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/view</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
				<filtering>false</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${jdk.version}</source><!-- 源代码使用的开发版本 -->
					<target>${jdk.version}</target><!-- 须要生成的目标class文件的编译版本 -->
					<encode>${project.build.sourceEncoding}</encode>
				</configuration>
			</plugin>
			<plugin>	<!-- 该插件的主要功能是进行项目的打包发布处理 -->
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>	<!-- 设置程序执行的主类 -->
					<mainClass>cn.mldn.microboot.StartSpringBootMain</mainClass>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
	<modules>
		<module>microboot-base</module>
		<module>microboot-advance</module>
		<module>microboot-error</module>
		<module>microboot-tomcat</module>
		<module>microboot-thymeleaf</module>
		<module>microboot-upload</module>
	</modules>
</project>
package cn.mldn.microboot.controller;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.mldn.microboot.util.controller.AbstractBaseController;

@Controller
public class UploadController extends AbstractBaseController {
	@RequestMapping(value = "/uploadPre", method = RequestMethod.GET)
	public String uploadPre() { // 经过model能够实现内容的传递
		return "upload_page";
	}
	@RequestMapping(value = "/show", method = RequestMethod.GET)
	public String show(String groupId, String fileId,Model model) throws Exception {
		// 经过ClassPath路径获取要使用的配置文件
		ClassPathResource classPathResource = new ClassPathResource(
				"fastdfs_client.conf");
		// 进行客户端访问的总体配置,须要知道配置文件的完整路径
		ClientGlobal.init(classPathResource.getClassLoader()
				.getResource("fastdfs_client.conf").getPath());
		// FastDFS的核心操做在于tracker处理上,因此此时须要定义Tracker客户端
		TrackerClient trackerClient = new TrackerClient();
		// 定义TrackerServer的配置信息
		TrackerServer trackerServer = trackerClient.getConnection();
		int ts = (int) (System.currentTimeMillis() / 1000);// 时间参考
		StringBuffer fileUrl = new StringBuffer();
		fileUrl.append("http://");
		fileUrl.append("fastdfs-tracker");
		fileUrl.append("/" + groupId + "/").append(fileId);
		fileUrl.append("?token=").append(
				ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key));
		fileUrl.append("&ts=").append(ts);
		System.out.println(fileUrl);
		trackerServer.close();
		model.addAttribute("image", fileUrl) ;
		return "upload_show" ;
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(String name, HttpServletRequest request)
			throws Exception {
		if (request instanceof MultipartHttpServletRequest) { // 若是你如今是MultipartHttpServletRequest对象
			MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> files = mrequest.getFiles("photo");
			Iterator<MultipartFile> iter = files.iterator();
			while (iter.hasNext()) {
				MultipartFile photo = iter.next();
				if (photo != null) { // 如今有文件上传
					// 若是要想进行上传则必定须要获取到文件的扩展名称
					String fileExtName = photo.getContentType().substring(
							photo.getContentType().lastIndexOf("/") + 1);
					// 经过ClassPath路径获取要使用的配置文件
					ClassPathResource classPathResource = new ClassPathResource(
							"fastdfs_client.conf");
					// 进行客户端访问的总体配置,须要知道配置文件的完整路径
					ClientGlobal.init(classPathResource.getClassLoader()
							.getResource("fastdfs_client.conf").getPath());
					// FastDFS的核心操做在于tracker处理上,因此此时须要定义Tracker客户端
					TrackerClient trackerClient = new TrackerClient();
					// 定义TrackerServer的配置信息
					TrackerServer trackerServer = trackerClient.getConnection();
					// 在整个FastDFS之中真正负责干活的就是Storage
					StorageServer storageServer = null;
					StorageClient1 storageClient = new StorageClient1(
							trackerServer, storageServer);
					// 定义上传文件的元数据
					NameValuePair[] metaList = new NameValuePair[3];
					metaList[0] = new NameValuePair("fileName",
							photo.getOriginalFilename());
					metaList[1] = new NameValuePair("fileExtName", fileExtName);
					metaList[2] = new NameValuePair("fileLength",
							String.valueOf(photo.getSize()));
					// 若是要上传则使用trackerClient对象完成
					String upload_file = storageClient.upload_file1(
							photo.getBytes(), fileExtName, metaList);
					System.out.println(upload_file);
					trackerServer.close();
				}
			}
		}
		return "upload-file";
	}
}

4.设置图片显示页面:apache

upload_show.htmltomcat

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<title>SpringBoot模版渲染</title>
	<script type="text/javascript" th:src="@{/js/main.js}"></script> 
	<link rel="icon" type="image/x-icon" href="/images/mldn.ico"/>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
	<img th:src="${image}"/>
</body>
</html>

5.每次显示图片的时候设置好groupId和fileId就能够实现图片的查看处理:服务器

upload_page.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<title>SpringBoot模版渲染</title>
	<script type="text/javascript" th:src="@{/js/main.js}"></script> 
	<link rel="icon" type="image/x-icon" href="/images/mldn.ico"/>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
	<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
		姓名:<input type="text" name="name"/><br/>
		照片:<input type="file" name="photo"/><br/>
		照片:<input type="file" name="photo"/><br/>
		照片:<input type="file" name="photo"/><br/>
		<input type="submit" value="上传"/>
	</form>
	<a th:href="@{/show(groupId='group1',fileId='M00/00/00/wKhEtVlTFc2ANT4kAALWT3AMif079.jpeg')}">查看照片</a>
	<a th:href="@{/show(groupId='group1',fileId='M00/00/00/wKhEtVlTFc2AUVINAAA9nfksZs0713.png')}">查看照片</a>
	<a th:href="@{/show(groupId='group1',fileId='M00/00/00/wKhEtVlTFc2AOgxGAC-AAARLh5I67.jpeg')}">查看照片</a>
</body> 
</html>

若是传递的内容是字符串必定要使用"'"声明,若是是数字则能够直接编写。

相关文章
相关标签/搜索