SpringBoot+Vue+Element+FastDFS实现图片的上传功能
共 2833字,需浏览 6分钟
·
2020-12-05 23:35
点击上方 Java老铁,并选择 设为星标
添加Maven依赖
<dependency>
<groupId>com.github.tobatogroupId>
<artifactId>fastdfs-clientartifactId>
<version>1.26.2version>
dependency>
编写配置文件
server:
port: 9009
spring:
application:
name: springBoot-upload
servlet:
multipart:
max-file-size: 5MB # 限制文件上传的大小
fdfs:
so-timeout: 1501 # 超时时间
connect-timeout: 601 # 连接超时时间
thumb-image: # 缩略图
width: 60
height: 60
tracker-list: # tracker地址:你的虚拟机服务器地址+端口(默认是22122)
- 192.168.206.140:22122
编写上传的service
@Service
public class UploadService {
private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);
private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif","image/png");
@Autowired
private FastFileStorageClient storageClient;
public String upload(MultipartFile file) {
//获取文件名称
String originalFilename = file.getOriginalFilename();
//校检文件的类型
String contentType = file.getContentType();
if (!CONTENT_TYPES.contains(contentType)){
LOGGER.info("文件类型不合法:{}",originalFilename);
return null;
}
try {
// 校验文件的内容
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (bufferedImage == null){
LOGGER.info("文件内容不合法:{}", originalFilename);
return null;
}
// 保存到服务器
//file.transferTo(new File("D:\\upload\\images\\" + originalFilename));
String ext = StringUtils.substringAfterLast(originalFilename, ".");
StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
// 生成url地址,返回
//return "http://127.0.0.1/" + originalFilename;
return "http://192.168.206.140/" + storePath.getFullPath();
} catch (IOException e) {
LOGGER.info("服务器内部错误:{}", originalFilename);
e.printStackTrace();
}
return null;
}
}
编写Controller
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping("/image")
public Result uploadImage(@RequestParam("file") MultipartFile file){
String url = this.uploadService.upload(file);
if (StringUtils.isBlank(url)) {
return new Result(true, StatusCode.OK,"上传失败");
}
return new Result(true, StatusCode.OK,"上传成功",url);
}
}
编写前端部分
前端使用了Vue加上ElementUI框架
<div>
<el-upload :action="uploadURL" list-type="picture" :on-preview="handlePreview" multiple>
<el-button size="small" type="primary">点击上传el-button>
el-upload>
<el-dialog :visible.sync="previewVisible" title="图片预览">
<img :src="previewPath" alt="" class="previewImg">
el-dialog>
div>
图片预览的逻辑
// 处理图片预览效果
handlePreview(file) {
console.log(file)
this.previewPath = file.response.data
this.previewVisible = true
},
测试
运行地址:http://localhost:8080/upload
界面
上传
可以一次上传多张图片,点击图片的名字还可以查看预览
前端代码地址:https://gitee.com/mytimelife/fastdfs_vue.git
注:图片来源网络,侵权,联系删除