需要的环境
maven+spring+linux(FastDFS-Nginx)
还需要一个封装的类
链接:https://pan.baidu.com/s/1cFR7zV0JqnYiWPmogCTamg
密码:e8wn
1.将图片传到服务器端
1)需要jar包的依赖commons-fileupload.jar/commons-io.jar
<dependency>
<groupId>fastdfs_client</groupId>
<artifactId>fastdfs_client</artifactId>
<version>1.25</version>
</dependency>
2)要在springmvc.xml中配制文件上传解析器
<!-- 图片上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242800"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
2、 将服务器端的数据写入FastDFS中
a) TrackerServer/TrackerClient/StorageServer/StorageClient
b) file_id:拼接上图片服务器的地址
需要在控制器(contaoller)
需要一个配制文件resource,也就是Linux系统中的地址
##图片上传地址
IMAGE_SERVER_URL=http://192.168.232.110/
需要一个配制文件clinet.conf
##FastDFS的端口号
tracker_server=192.168.244.110:22122
//图片上传,所有的图片上传都要进过这个路径
//注解
@Value("${IMAGE_SERVER_URL}")
private String IMAGE_SERVER_URL;
@ResponseBody
@RequestMapping("pic/upload")
public Map<Object,Object> upload(MultipartFile uploadFile){
//将客户端的文件上传到服务器端
byte[] content=null;
Map<Object,Object> result =new HashMap<Object,Object>();
try {
//转换成字节数组
content=uploadFile.getBytes();
//2.将文件上传到FastDFS文件系统中
//获取当前项目中upload目录的绝对路径
String orgName=uploadFile.getOriginalFilename();//获取文件名**.jpg
String ext=FilenameUtils.getExtension(orgName);//获取文件后缀名
String conf="classpath:config/client.conf";
FastDFSClient fastDFSClient = new FastDFSClient(conf);
//执行上传后返回的一个file_id
String file_id = fastDFSClient.uploadFile(content, ext);
//拼接地址
String url = IMAGE_SERVER_URL + file_id;
System.out.println(url);
result.put("error", 0);
result.put("url", url);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
result.put("error", 1);
result.put("message", "图片上传失败");
return result;
}
return result;
}
在Spring中读取配置文件的值
<!--加载配制文件 -->
<context:property-placeholder location="classpath:config/resources.properties"/>
这样图片就上传好了;
补充:也可以用一个测试类来验证
凡是图片上传
import java.io.IOException;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.junit.Test;
public class testUpload {
@Test
public void test1() throws IOException, MyException{
ClientGlobal.init("E:/softwarePath/eclipse/myshop-manager-web/src/main/resources/config/client.conf");
//1.创建Tracker客户端
TrackerClient client=new TrackerClient();
//2.创建一个Tracker服务器对象
TrackerServer server=client.getConnection();
//3.创建storageserver
StorageServer storageServer=null;
//4.创建StorageClient
StorageClient storageClient=new StorageClient(server, storageServer);
//5.上传文件
String[] result=storageClient.upload_file("E:/myTest/1.jpg", "jpg",null);
for (String s : result) {
System.out.println(s);
}
}
}