八、文件的下載和刪除功能
8.1.FastDFSClient.java
@Slf4j
public class FastDFSClient {
static {
//加載fastDFS客戶端的配置文件
try {
ClientGlobal.initByProperties("config/fastdfs-client.properties");
log.info("network_timeout = {} ms", ClientGlobal.g_network_timeout);
log.info("charset= {}", ClientGlobal.g_charset);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
/**
* 上傳文件
*
* @param file
* @param fastDFSFile
* @return
* @throws IOException
*/
public static FastDfsFile upload(MultipartFile file, FastDfsFile fastDFSFile) throws IOException {
byte[] file_buff = null;
//把文件轉(zhuǎn)成輸入流
InputStream inputStream = file.getInputStream();
if (inputStream != null) {
//獲取輸入流中可讀取的數(shù)據(jù)大小
int len = inputStream.available();
//創(chuàng)建足夠大的緩沖區(qū)
file_buff = new byte[len];
//一次性把輸入流中的數(shù)據(jù)全都讀入到緩沖區(qū)file_buff,那file_buff就要足夠大,占用內(nèi)存也會(huì)很大
inputStream.read(file_buff);
}
//關(guān)閉輸入流
inputStream.close();
//通過fastDSF的client代碼訪問tracker和storage
try {
//創(chuàng)建tracker的客戶端
TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
//通過TrackerClient對象獲取TrackerServer信息
TrackerServer trackerServer = trackerClient.getTrackerServer();
StorageServer storageServer = null;
//定義storage的客戶端,建立與Storage服務(wù)器的連接
StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);
//文件元信息
NameValuePair[] metaList = new NameValuePair[1];
metaList[0] = new NameValuePair("fileName", fastDFSFile.getFileName());
//執(zhí)行上傳
String fileId = storageClient.upload_file1(file_buff, fastDFSFile.getExt(), metaList);
log.info("upload success. file id is: {}", fileId);
fastDFSFile.setFileId(fileId);
fastDFSFile.setFilePath(fileId);
fastDFSFile.setFileSize(file.getSize());
fastDFSFile.setCreateTime(LocalDateTime.now());
fastDFSFile.setUpdateTime(LocalDateTime.now());
//通過調(diào)用service及dao將文件的路徑存儲(chǔ)到數(shù)據(jù)庫中
//關(guān)閉storage客戶端
storageClient.close();
return fastDFSFile;
} catch (Exception e) {
log.error("上傳文件失敗:", e);
e.printStackTrace();
return null;
}
}
/**
* 刪除文件
*
* @param file_id
* @return
* @throws IOException
* @throws MyException
*/
public static Boolean delete(String file_id) throws IOException, MyException {
//通過fastDSF的client代碼訪問tracker和storage
//創(chuàng)建tracker的客戶端
TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
//通過TrackerClient對象獲取TrackerServer信息
TrackerServer trackerServer = trackerClient.getTrackerServer();
StorageServer storageServer = null;
//定義storage的客戶端,建立與Storage服務(wù)器的連接
StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);
//查詢文件
//upload success. file id is: group1/M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
String[] splitStr = file_id.split("/");
String group_name = splitStr[0];//group1
String remoteFileName = "";//M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
for (int i = 1; i < splitStr.length; i++) {
remoteFileName += splitStr[i];
if (i != splitStr.length - 1) {
remoteFileName += "/";
}
}
log.info("group_name : {}", group_name);
log.info("remoteFileName : {}", remoteFileName);
FileInfo fileInfo = storageClient.query_file_info(group_name, remoteFileName);
log.info("fileInfo = {}", fileInfo);
if (fileInfo == null) {
log.info("您刪除的文件信息不存在,請核對后再次刪除......");
return false;
}
storageClient.delete_file1(file_id);
log.info("刪除成功");
//關(guān)閉storage客戶端
storageClient.close();
return true;
}
/**
* 下載文件
*
* @param file_id
* @throws IOException
* @throws MyException
*/
public static byte[] downloadFastFile(String file_id) throws IOException, MyException {
//通過fastDSF的client代碼訪問tracker和storage
//創(chuàng)建tracker的客戶端
TrackerClient trackerClient = new TrackerClient(ClientGlobal.getG_tracker_group());
//通過TrackerClient對象獲取TrackerServer信息
TrackerServer trackerServer = trackerClient.getTrackerServer();
StorageServer storageServer = null;
//定義storage的客戶端,建立與Storage服務(wù)器的連接
StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);
//查詢文件
//upload success. file id is: group1/M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
String[] splitStr = file_id.split("/");
String group_name = splitStr[0];//group1
String remoteFileName = "";//M00/00/00/wKjljWXHAauARHa2AAWwwNOt0hY257.png
for (int i = 1; i < splitStr.length; i++) {
remoteFileName += splitStr[i];
if (i != splitStr.length - 1) {
remoteFileName += "/";
}
}
log.info("group_name : {}", group_name);
log.info("remoteFileName : {}", remoteFileName);
FileInfo fileInfo = storageClient.query_file_info(group_name, remoteFileName);
log.info("fileInfo = {}", fileInfo);
if (fileInfo == null) {
log.info("您下載的文件信息不存在,請核對后再次下載......");
return null;
}
//下載操作,傳文件id返回字節(jié)流
byte[] bytes = storageClient.download_file1(file_id);
//關(guān)閉storage客戶端
storageClient.close();
return bytes;
}
}
8.2.FileServerController.java
@Slf4j
@RestController
@RequestMapping("/fastDFSFile")
public class FileServerController {
@Resource
private FastDfsFileService fastDfsFileService;
@Resource
private FastDfsFileTypeService fastDfsFileTypeService;
@PostMapping("/upload")
@ResponseBody
public R upload(@RequestParam("file") MultipartFile file) throws IOException {
//將文件先存儲(chǔ)在web服務(wù)器上(本機(jī)),在調(diào)用fastDFS的client將文件上傳到 fastDFS服務(wù)器
FastDfsFile fastDFSFile = new FastDfsFile();
String contentType = file.getContentType();
//檢驗(yàn)當(dāng)前文件是否在上述集合中
log.info("上傳的文件類型為:{}", contentType);
int count = fastDfsFileTypeService.selectByFileType(contentType);
if (count < 1) {
log.info("不支持此文件類型上傳 : {}", contentType);
return R.error().setCode(208).setMessage("不支持此文件類型上傳 : " + contentType);
}
log.info("此文件類型為 : {}", contentType);
fastDFSFile.setFileType(contentType);
//文件原始名稱
String originalFilename = file.getOriginalFilename();
log.info("原始文件名稱 : {}", originalFilename);
fastDFSFile.setFileName(originalFilename);
//文件擴(kuò)展名比如22.jpg
String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
log.info("文件類型 = {}", filenameExtension);//jpg
if (filenameExtension == null) {
return R.error().setCode(208).setMessage("此文件沒有文件擴(kuò)展名");
}
fastDFSFile.setExt(filenameExtension);
//新文件名稱
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + filenameExtension;
log.info("新文件名稱 = {}", fileName);
FastDfsFile fastDfsFile1 = FastDFSClient.upload(file, fastDFSFile);
if (fastDfsFile1 != null) {
fastDfsFileService.save(fastDfsFile1);
Long id = fastDfsFileService.selectByFileId(fastDfsFile1.getFileId());
fastDfsFile1.setId(id);
return R.ok().setCode(200).setMessage("上傳成功").data("fastDfsFile", fastDfsFile1);
}
return R.error().setCode(208).setMessage("上傳失敗");
}
//restful風(fēng)格
@DeleteMapping()
public R delete(@RequestParam("id") Long id, @RequestParam("fileId") String fileId) throws MyException, IOException {
Boolean result = FastDFSClient.delete(fileId);
if (!result) {
log.info("刪除失敗");
return R.error().setCode(208).setMessage("刪除失敗");
}
int count = fastDfsFileService.deleteFastDfsFileById(id);
if (count < 1) {
log.info("刪除失敗");
return R.error().setCode(208).setMessage("刪除失敗");
}
log.info("刪除成功");
return R.ok().setCode(200).setMessage("刪除成功");
}
@GetMapping()
public void downloadfile(HttpServletResponse response, String fileId, String fileName) throws IOException, MyException {
if (fileId == null) return;
log.info("fileName = {}", fileName);
response.setContentType("application/force-download;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
byte[] bytes = FastDFSClient.downloadFastFile(fileId);
FileInputStream fis = null;
log.info("fileId = {}", fileId);
int len = 0;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
if (bytes == null) {
return;
}
log.info("success");
outputStream.write(bytes);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@GetMapping("/getPageFastImg/{page}/{limit}")
public R getPageFastImg(@PathVariable int page, @PathVariable int limit) {
PageBean<FastDfsFile> pageBean = fastDfsFileService.findFastDfsFileByPage(page, limit);
return R.ok().setCode(200).setMessage("查詢成功").data("pageBean", pageBean);
}
}
8.3.Vue的fast.js
import request from "../../utils/request";
const api_name = '/fastDFSFile'
export default {
//上傳圖片
uploadImg() {
return request({
url: `${api_name}`,
method: 'post',
})
},
getPageFastImg(page, limit) {
return request({
url: `${api_name}/getPageFastImg/${page}/${limit}`,
method: 'get',
})
},
getNextPageFastImg(page, limit) {
return request({
url: `${api_name}/getPageFastImg/${page}/${limit}`,
method: 'get',
})
},
//restful風(fēng)格 ?id=123&fileId=456
deleteFastImg(id, fileId) {
return request({
url: `${api_name}`,
method: 'delete',
params: {
"id": id,
"fileId": fileId
}
})
},
getFileSrc(fileId) {
return request({
url: `${api_name}`,
method: 'get',
params: {
"fileId": fileId
},
responseType: 'blod'
})
},
}
8.4.fastdfsimg.vue
<template>
<div>
<h2>圖片管理</h2>
<!--圖片列表-->
<el-table
size="small"
style="margin: 30px;"
empty-text="無數(shù)據(jù)"
:data="imgList"
highlight-current-row v-loading="loading" border element-loading-text="拼命加載中">
<el-table-column align="center" sortable prop="filePath" label="文件路徑" width="450"></el-table-column>
<el-table-column align="center" sortable prop="fileSize" label="文件大小" width="100"></el-table-column>
<el-table-column align="center" sortable prop="fileName" label="文件名" width="130"></el-table-column>
<el-table-column align="center" sortable prop="ext" label="擴(kuò)展名" width="100"></el-table-column>
<el-table-column align="center" sortable prop="fileType" label="文件類型" width="100"></el-table-column>
<el-table-column align="center" sortable prop="filePath" label="預(yù)覽圖片" width="100">
<template slot-scope="scope">
<img :src="getImageUrl(scope.row.filePath)" style="max-width: 100px;max-height: 100px" alt="圖標(biāo)"/>
</template>
</el-table-column>
<el-table-column label="操作" width="200" align="center">
<template slot-scope="scope">
<el-button type="text" size="small" icon="el-icon-download" @click="getFileSrc(scope.row)">下載</el-button>
<el-popconfirm title="確定刪除嗎?" @confirm="handleDeleteOne(scope.row)">
<template #reference>
<el-button type="danger" size="small" icon="el-icon-delete">刪除</el-button>
</template>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!-- 分頁 -->
<el-pagination class="pagination" style="text-align: center;margin-top: 50px"
layout="prev, pager, next"
:current-page="page"
:total="total"
:page-size="limit"
@current-change="fetchData">
</el-pagination>
</div>
</template>
<script>
import fastApi from "@/api/fastdfs/fast";
import request from "../../utils/request";
export default {
name: "FastdfsImg",
data() {
return {
total: 0, // 數(shù)據(jù)庫中的總記錄數(shù)
page: 1, // 默認(rèn)頁碼
limit: 5, // 每頁記錄數(shù)
imgList: {},
//imagePath: 'http://192.168.229.141/', // 圖片的基礎(chǔ)路徑
}
},
created() {
this.init()
},
methods: {
init() {
fastApi.getPageFastImg(this.page, this.limit).then(response => {
this.imgList = response.data.pageBean.lists
this.total = response.data.pageBean.totalCount
})
},
//獲取圖片路徑
getImageUrl(filePath) {
//return `${this.imagePath}${filePath}`; // 拼接圖片路徑
return this.$baseImagePath + '/' + filePath; // 拼接圖片路徑
},
//下一頁
fetchData(page) {
this.page = page
fastApi.getNextPageFastImg(this.page, this.limit).then(response => {
this.imgList = response.data.pageBean.lists
this.total = response.data.pageBean.totalCount
})
},
// 單選刪除
handleDeleteOne(FastDfsFile) {
fastApi.deleteFastImg(FastDfsFile.id, FastDfsFile.fileId).then(response => {
this.$message.success(response.message)
this.init()
})
},
// 下載文件
getFileSrc(FastDfsFile) {
//window.open(this.$baseImagePath+'/'+FastDfsFile.fileId,"_blank");
/*fastApi.downloadFastImg(FastDfsFile.fileId).then(response=>{
this.$message.success(response.message)
})*/
window.location.href = request.defaults.baseURL + '/fastDFSFile?fileId=' + FastDfsFile.fileId + '&&fileName=' + FastDfsFile.fileName;
}
},
}
</script>
<style scoped>
</style>
8.5.效果
文章來源地址http://www.zghlxwxcb.cn/news/detail-829167.html
九、總結(jié)
- 案例有些不足
- 功能太簡單
- 功能復(fù)雜可以做一個(gè)類似網(wǎng)盤的文件管理系統(tǒng)
- 僅僅學(xué)習(xí)使用某些功能
- 暫不深入開發(fā)
- 有興趣的伙伴可以嘗試一番
- 類似于阿里云oss
endl
文章來源:http://www.zghlxwxcb.cn/news/detail-829167.html
到了這里,關(guān)于分布式文件系統(tǒng) SpringBoot+FastDFS+Vue.js【四】的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!