百度网盘:
链接:https://pan.baidu.com/s/1ASbiB4pPl5Ez-v8zfhAPhw
提取码:8zwt
一。
将此工程(fastdfs_client)导入到eclipse中,然后update一下,之后install此项目,就可以将此项目打包成jar包,添加到中央仓库,另外需要在web工程中添加相关依赖,即可
二。
创建配置文件client.conf 在src/main/resources下创建一个recource(Folder),在其中创建配置文件client.conf
上传测试类
public class TestPicture {
@Test
public void testUpload() throws FileNotFoundException, IOException, MyException{
//1.初始化,读取配置文件,上传的服务器
ClientGlobal.init("C:/1701A/taoTaoworkspace/taotao-manager-web/src/main/resources/resource/client.conf");
//2.创建tarkerclient对象
TrackerClient trackerClient = new TrackerClient();
//3.创建trackerServer对象 ,获取连接
TrackerServer trackerServer = trackerClient.getConnection();
//4.创建StorageServer
StorageServer storageServer = null;
//5.创建一个StorageClient对象,需要两个参数TrackerServer对象、StorageServer的引用
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
//6.上传文件 文件地址, 文件类型 null
String[] str = storageClient.upload_file("D:/image/20.jpg", "jpg", null);
for (String string : str) {
System.out.println(string);
}
}
}
运行测试类后在后台显示图片的地址,在浏览器上输入即可
三。
运用工具类FastDFSClient 在web工程中添加一个包utils。将工具类放入里面,因为这个工具类只是在web工程中使用,就不放入到common工程中
package com.taotao.utils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
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);
}
/**
* 上传文件方法
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param fileName 文件全路径
* @param extName 文件扩展名,不包含(.)
* @param metas 文件扩展信息
* @return
* @throws Exception
*/
public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
String result = storageClient.upload_file1(fileName, extName, metas);
return result;
}
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);
}
/**
* 上传文件方法
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param fileContent 文件的内容,字节数组
* @param extName 文件扩展名
* @param metas 文件扩展信息
* @return
* @throws Exception
*/
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
String result = storageClient.upload_file1(fileContent, extName, metas);
return result;
}
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);
}
}
编写测试类
@Test
public void testUploadUtils() throws Exception{
FastDFSClient fastDFSClient = new FastDFSClient("C:/1701A/taoTaoworkspace/taotao-manager-web/src/main/resources/resource/client.conf");
String str = fastDFSClient.uploadFile("D:/image/vv.jpg");
System.out.println(str);
}
测试结果
四。
图片上传功能使用到富文本编辑器:KindEdit
返回格式:
//成功时
{
"error" : 0,
"url" : "http://www.example.com/path/to/file.ext"
}
//失败时
{
"error" : 1,
"message" : "错误信息"
}
业务逻辑:
1、接收页面传递的图片信息uploadFile
2、把图片上传到图片服务器。使用封装的工具类实现。需要取文件的内容和扩展名。
3、图片服务器返回图片的url
4、将图片的url补充完整,返回一个完整的url。
5、把返回结果封装到一个Map对象中返回。
五。
创建一个基础的ip,resource.properties 根据服务器不同可以修改
然后在springmvc.xml中添加:
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:resource/resource.properties" />
六。
JsonUtils工具类:将map转换为json
package com.taotao.utils;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.result.TaotaoResult;
/**
* 淘淘商城自定义响应结构
*/
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param clazz 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
七。
在pom.xml添加上传所需的依赖
<!-- 文件上传组件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
在springmvc.xml中添加图片上传的约束:图片的大小
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
Controller:
package com.taotao.controller;
import java.util.HashMap;
import java.util.Map;
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;
import com.taotao.utils.FastDFSClient;
import com.taotao.utils.JsonUtils;
@Controller
public class PictureController {
@Value("${IMAGE_BASE_URL}")
private String IMAGE_BASE_URL;
@RequestMapping("/pic/upload")
@ResponseBody
public String uploadFile(MultipartFile uploadFile){
//获取到文件路径
String originalFilename = uploadFile.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
try {
//读取配置文件
FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/client.conf");
//上传后返回的路径
String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
//前台页面展示 192.168
String pathUrl = IMAGE_BASE_URL+path;//返回的url
Map map = new HashMap<>();
map.put("error", 0);
map.put("url", pathUrl);
return JsonUtils.objectToJson(map);//转为json
} catch (Exception e) {
e.printStackTrace();
Map map = new HashMap<>();
map.put("error", 1);
map.put("message", "图片上传失败");
return JsonUtils.objectToJson(map);//转为json
}
}
}