SpringBoot+Vue+Element+FastDFS實(shí)現(xiàn)圖片的上傳功能
點(diǎn)擊上方?Java老鐵,并選擇?設(shè)為星標(biāo)
添加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 # 超時(shí)時(shí)間
connect-timeout: 601 # 連接超時(shí)時(shí)間
thumb-image: # 縮略圖
width: 60
height: 60
tracker-list: # tracker地址:你的虛擬機(jī)服務(wù)器地址+端口(默認(rèn)是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 {
// 校驗(yàn)文件的內(nèi)容
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (bufferedImage == null){
LOGGER.info("文件內(nèi)容不合法:{}", originalFilename);
return null;
}
// 保存到服務(wù)器
//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("服務(wù)器內(nèi)部錯(cuò)誤:{}", 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">點(diǎn)擊上傳el-button>
el-upload>
<el-dialog :visible.sync="previewVisible" title="圖片預(yù)覽">
<img :src="previewPath" alt="" class="previewImg">
el-dialog>
div>
圖片預(yù)覽的邏輯
// 處理圖片預(yù)覽效果
handlePreview(file) {
console.log(file)
this.previewPath = file.response.data
this.previewVisible = true
},
測(cè)試
運(yùn)行地址:http://localhost:8080/upload
界面
上傳

可以一次上傳多張圖片,點(diǎn)擊圖片的名字還可以查看預(yù)覽

前端代碼地址:https://gitee.com/mytimelife/fastdfs_vue.git
注:圖片來源網(wǎng)絡(luò),侵權(quán),聯(lián)系刪除
