最重要一点要在CentOS的docker中进行,macOS会有很多问题。
1.拉取镜像
docker pull qbanxiaoli/fastdfs
2.运行镜像
docker run -d --privileged=true --net=host --name=fastdfs -e IP=172.16.200.168 -e WEB_PORT=80 -v /root/docker/fastdfs:/var/local/fdfs qbanxiaoli/fastdfs
其中172.16.200.168改为宿主机CentOS的IP
/root/docker/fastdfs改为宿主机上的存在的目录
3.docker中测试上传
A.进入docker:
docker exec -it fastdfs /bin/bash
B.创建文件
echo "Hello FastDFS!">index.html
C.fastdfs自带命令上传
fdfs_test /etc/fdfs/client.conf upload index.html
D.上传成功返回地址输入浏览器即可
http://172.16.200.168/group1/M00/00/00/rBDIqF0Z112AYqC-AAAADyBAGsI06_big.html
E.如果无法访问172.16.200.168机器可以把防火墙关闭再访问
4.SpringBoot中使用代码实现
A.依赖
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.4</version>
</dependency>
B.配置
#FastDfs
fdfs.so-timeout=1500
fdfs.connect-timeout=6000
fdfs.tracker-list=172.16.200.168:22122
fdfs.pool.jmx-enabled=false
fastDfs.host=http://172.16.200.168/
fdfs.thumb_image.width = 150
fdfs.thumb_image.height = 150
其中172.16.200.168为docker宿主机的地址,有可能是在虚拟机中
C.启动类
加上注解
@Import(FdfsClientConfig.class)
D.使用
后台
@Service
public class PictureService {
@Autowired
private FastFileStorageClient fileStorageClient;
@Value("${fastDfs.host}")
private String hostIp;
public String uploadPic(MultipartFile file) {
try {
StorePath storePath = fileStorageClient.uploadFile(
file.getInputStream(),
file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()), null);
String fileUrl = hostIp + storePath.getFullPath();
return fileUrl;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@PostMapping("/testUpload")
public Result<String> testUpload(@RequestBody MultipartFile file) {
String url = pictureService.uploadPic(file);
return new Result<>(true, StatusCode.OK, "成功", url);
}
E.前端实现
ElementUI的el-upload组件
<el-upload
action="http://localhost:9011/goods/testUpload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
数据结构
fileList: [
{
name: 'food.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
},
{
name: 'food2.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
}
],