element-ui文件上傳下載組件:
具備上傳、下載和刪除功能。
不自動上傳,附件選擇后只將文件加入待上傳列表,點擊確認上傳按鈕后上傳到后臺服務器,已上傳的文件通過表格的形式展示在上方表格中。
刪除和上傳權(quán)限可配置。
效果如下:
代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-527313.html
/*
* @Description: element-ui文件上傳下載組件(不自動上傳)
* @Author: yiwenli
* @Date: 2023-03-30
*/
Vue.component('fileUpload', {
name: 'fileUpload',
template: /* html */ `<div>
<div>已上傳文件列表</div>
<el-table :data="uploadedFileList" :show-header="false">
<el-table-column prop="fileName" width="300" align="center"></el-table-column>
<el-table-column prop="operate" width="200" align="center">
<template slot-scope="scope">
<el-button class="el-icon-download" type="text" @click="fileDownload(scope.row)">下載</el-button>
<el-button class="el-icon-delete" type="text" @click="fileDeleteInServer(scope.row)" v-if="deleteAble">刪除</el-button>
</template>
</el-table-column>
</el-table>
<el-form-item v-if="uploadAble">
<el-upload
action="#"
:auto-upload="false"
:multiple="true"
:file-list="toUploadFileList"
:on-change="fileChange"
:on-remove="fileRemove"
>
<el-button slot="trigger" size="small" type="primary">附件選擇</el-button>
<el-button size="small" plain @click="fileUpload">確認上傳</el-button>
</el-upload>
</el-form-item>
</div>`,
props: {
// 原始文件數(shù)據(jù)
fileList: {
type: Array,
required: true,
default: () => [],
},
// 上傳功能是否可用
uploadAble: {
type: Boolean,
required: false,
default: true,
},
// 刪除功能是否可用
deleteAble: {
type: Boolean,
required: false,
default: true,
},
},
data() {
return {
// 已上傳文件列表
uploadedFileList: [],
// 待上傳文件列表
toUploadFileList: [],
};
},
computed: {
// 上傳路徑
uploadUrl() {
return requestUrlBase('/file/fileUpload');
},
// 刪除路徑
deleteUrl() {
return requestUrlBase('/file/deleteFile');
},
// 下載路徑
downloadUrl() {
return requestUrlBase('/file/downLoadFile');
},
},
watch: {
uploadedFileList() {
this.$emit('update:fileList', this.uploadedFileList);
},
fileList() {
this.uploadedFileList = this.fileList;
},
},
created() {
this.uploadedFileList = this.fileList;
},
methods: {
/**
* 文件上傳
*/
fileUpload() {
if (this.toUploadFileList.length === 0) {
this.$message.error('請先選擇至少1個文件再上傳');
return;
}
let formData = new FormData();
this.toUploadFileList.forEach((item) => {
formData.append('file', item.raw);
});
$http({
url: this.uploadUrl,
method: 'post',
data: formData,
headers: { 'Content-Type': 'multipart/form-data' },
})
.then(({ data }) => {
// 1、更新已上傳文件列表
this.uploadedFileList = this.uploadedFileList.concat(data);
// 2、更新待上傳文件列表
let returnFileMap = new Map(data.map((value) => [value.fileName, value.fileId]));
this.toUploadFileList = this.toUploadFileList
.filter((item) => !returnFileMap.has(item.name))
.map((item) => {
item.status = 'error';
return item;
});
this.$message.success('附件上傳完成');
})
.catch((e) => {
this.$message.error(e.message || '附件上傳失敗');
});
},
/**
* 文件修改
* @param {*} file 當前操作文件對象
* @param {*} fileList 文件列表
*/
fileChange(file, fileList) {
this.toUploadFileList = fileList;
},
/**
* 文件刪除
* @param {Object} file 當前操作文件對象
* @param {Array} fileList 文件列表
*/
fileRemove(file, fileList) {
this.toUploadFileList = fileList;
},
/**
* 文件從服務器端刪除
* @param {Object} file 文件對象
*/
fileDeleteInServer(file) {
this.$confirm('確定刪除?', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning',
})
.then(() => {
$http({
url: this.deleteUrl,
method: 'get',
params: requestParam(file, 'get'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(() => {
this.$message.success('文件刪除成功');
this.uploadedFileList.splice(
this.uploadedFileList.findIndex((item) => item.fileId === file.fileId),
1
);
})
.catch((e) => {
this.$message.error(e.message || '文件刪除失敗');
});
})
.catch(() => {
this.$message({
type: 'info',
message: '已取消刪除',
});
});
},
/**
* 文件下載
* @param {Object} file 文件對象
*/
fileDownload(file) {
let params = {
fileId: file.fileId,
fileName: file.fileName,
userOrgId: Session.get('userInfo').orgId,
};
this.postDownloadFile(params, this.downloadUrl);
},
/**
* 以post方式傳參并下載文件
* @param {Object} params 請求需要的參數(shù)
* @param {String} url 請求url地址
*/
postDownloadFile(params, url) {
// params是post請求需要的參數(shù),url是請求url地址
const form = document.createElement('form');
form.style.display = 'none';
form.action = url;
form.method = 'post';
document.body.appendChild(form);
// 動態(tài)創(chuàng)建input并給value賦值
for (const key in params) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
form.submit();
form.remove();
},
},
});
<file-upload
:file-list.sync="fileList"
:upload-able="true"
:delete-able="true"
></file-upload>
后端:文章來源地址http://www.zghlxwxcb.cn/news/detail-527313.html
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.ieslab.model.Result;
import com.ieslab.pfjawebsvr.modules.file.domain.FileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* @author
* @ClassName FileOpController
* @Description 附件上傳下載
* @date 2022年03月16日 14:20
*/
@Api(tags = "附件上傳下載")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
@ApiOperation("附件上傳")
@PostMapping("/fileUpload")
public Result upLoadFile(@RequestHeader("userOrgId") String userOrgId, @RequestParam("file") MultipartFile[] files) {
if (files.length == 0) {
return Result.error("文件為空");
}
if (ObjectUtil.isNull(userOrgId)) {
userOrgId = "null";
}
List<FileVO> fileVOList = new ArrayList<>();
try {
String basePath = System.getenv("PFJA_HOME") + "/file/" + userOrgId + "/";
for (MultipartFile multipartFile : files) {
String fileName = multipartFile.getOriginalFilename();
//生成文件唯一has256值
String hashValue = DigestUtil.sha256Hex(multipartFile.getBytes());
String filePath = basePath + FileNameUtil.getPrefix(fileName) + "&" + hashValue + "." + FileNameUtil.getSuffix(fileName);
File file = FileUtil.file(filePath);
//實現(xiàn)文件存儲
FileUtil.writeBytes(multipartFile.getBytes(), file);
fileVOList.add(new FileVO(hashValue, fileName));
}
return Result.ok(fileVOList);
} catch (Exception e) {
return Result.error(e.getMessage());
}
}
@ApiOperation("附件下載")
@PostMapping(value = "/downLoadFile")
public void downLoadFile(@RequestParam("userOrgId") String userOrgId, @RequestParam("fileId") String fileId, @RequestParam("fileName") String fileName, HttpServletResponse response) {
if (ObjectUtil.isNull(userOrgId)) {
userOrgId = "null";
}
String basePath = System.getenv("PFJA_HOME") + "/file/" + userOrgId + "/";
try {
// 創(chuàng)建輸出流對象
ServletOutputStream outputStream = response.getOutputStream();
//以字節(jié)數(shù)組的形式讀取文件
String filePath = basePath + FileNameUtil.getPrefix(fileName) + "&" + fileId + "." + FileNameUtil.getSuffix(fileName);
byte[] bytes = FileUtil.readBytes(filePath);
// 設置返回內(nèi)容格式
response.setContentType("application/octet-stream");
// 把文件名按UTF-8取出并按ISO8859-1編碼,保證彈出窗口中的文件名中文不亂碼
// 中文不要太多,最多支持17個中文,因為header有150個字節(jié)限制。
// 這一步一定要在讀取文件之后進行,否則文件名會亂碼,找不到文件
fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
// 設置下載彈窗的文件名和格式(文件名要包括名字和文件格式)
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 返回數(shù)據(jù)到輸出流對象中
outputStream.write(bytes);
// 關(guān)閉流對象
IoUtil.close(outputStream);
} catch (Exception e) {
Result.error(e.getMessage());
}
}
@ApiOperation("附件刪除")
@GetMapping("/deleteFile")
public Result deleteFile(@RequestHeader("userOrgId") String userOrgId, @RequestParam("fileId") String fileId, @RequestParam("fileName") String fileName) {
String basePath = System.getenv("PFJA_HOME") + "/file/" + userOrgId + "/";
String filePath = basePath + FileNameUtil.getPrefix(fileName) + "&" + fileId + "." + FileNameUtil.getSuffix(fileName);
File file = FileUtil.file(filePath);
if (file.exists()) {
boolean delete = file.delete();
return Result.ok(delete);
} else {
return Result.ok(true);
}
}
}
到了這里,關(guān)于element-ui文件上傳下載組件+后臺對應接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!