若依自定义文件上传下载

前端核心参数

deleteFilePath: [],

fileData: '',

upload: {

// 是否禁用上传

isUploading: false,

// 设置上传的请求头部

headers: { Authorization: "Bearer " + getToken() },

// 上传的地址

url: process.env.VUE_APP_BASE_API + "/system/ball/upload/file",

// 上传的文件列表

fileList: []

},

==================

<el-col :span="8">

<el-form-item label="上传附件" prop="urlPath">

<el-upload ref="upload" accept=".jpg, .png, .txt, .xlsx, .doc, .docx, .xls, .pdf, .zip, .rar"

:action="upload.url" multiple :http-request="HttpUploadFile" :headers="upload.headers"

:file-list="upload.fileList" :on-remove="handleRemove" :on-success="handleFileSuccess"

:on-change="changeFileList" :data="getfileData()" :auto-upload="false" :name="upload.fileName">

<el-button slot="trigger" size="small" type="primary">选取文件</el-button>

</el-upload>

<!-- <file-upload v-model="form.urlPath" /> -->

</el-form-item>

</el-col>

=============================

<el-table-column label="任务附件" align="center">

<template slot-scope="scope">

<el-link type="primary" style="margin-right:10px" v-for=" item in scope.row.sysXmglFiles " :key="item.id"

@click.prevent="downloadFile(item)">{{ item.fileName }}</el-link>

</template>

</el-table-column>

=========================

原表单事件

/** 修改按钮操作 */

handleUpdate(row) {

this.reset();

this.options.model.splice(this.options.model.indexOf(row.model), 1);

const id = row.id || this.ids

readTaskFile(row.id).then(response => {

this.upload.fileList = response.data

getBall(id).then(response => {

this.upload.fileList = response.data.sysXmglFiles

this.form = response.data;

this.open = true;

this.title = "修改ball";

});

})

},

/** 提交按钮 */

submitForm() {

this.$refs["form"].validate(valid => {

if (valid) {

if (this.form.inquiryId != null) {

updateInquiry(this.form).then(response => {

// 删除附件

var deleteFilePaths = this.deleteFilePath;

if (deleteFilePaths.length > 0) {

deleteFile(deleteFilePaths);

}

this.submitUpload()

this.$modal.msgSuccess("修改成功");

this.open = false;

this.open2 = false;

this.getList();

});

} else {

addInquiry(this.form).then(response => {

this.form.inquiryId = response.data

this.submitUpload()

this.$modal.msgSuccess("新增成功");

this.open = false;

this.open2 = false;

this.getList();

});

}

}

});

================

// 文件操作

// 下载

downloadFile(item) {

console.log(item)

this.download('system/ball/download/resource', {

filePath: item.filePath,

}, item.fileName)

},

//文件上传成功后的钩子函数

handleFileSuccess(response, file, fileList) {

this.upload.isUploading = false;

this.upload.fileList = []

this.$modal.msgSuccess(response.msg);

},

//fileList长度改变时触发

changeFileList(file, fileList) {

this.upload.fileList = fileList

console.log(this.upload.fileList)

},

getfileData() {

//此处的form是表单中的其它绑定值

},

handleRemove(file, fileList) {

this.upload.fileList = fileList

this.deleteFilePath.push(file.filePath)

console.log(this.upload.fileList)

},

submitUpload() {

//创建FormData对象,用于携带数据传递到后端

this.fileData = new FormData()

this.$refs.upload.submit();

this.fileData.append("data", JSON.stringify(this.form));

// console.log(this.form)

this.fileData.append("headers", { Authorization: "Bearer " + getToken() });

this.fileData.append("withCredentials", false)

this.fileData.append("filename", "file");

var i = this.fileData.get("files")

if (i != undefined) {

//此处执行调用发送请求

uploadFile(this.fileData).then((res) => {

if (res.code === 200) {

this.upload.isUploading = false;

this.upload.fileList = []

// this.$modal.msgSuccess(res.msg);

this.open = false;

this.getList();

this.getList2();

}

})

} else {

this.open = false;

this.getList();

this.getList2();

//如果没有文件要上传在此处写逻辑

}

},

HttpUploadFile(file) {

this.fileData.append('files', file.file); // append增加数据

},

============================

后端接口

查询赋值

复制代码
@RequiresPermissions("system:ball:list")
@GetMapping("/list")
public TableDataInfo list(SysBall sysBall) {

    startPage();
    List<SysBall> list = sysBallService.selectSysBallList(sysBall);
    /*构造回显文件列表*/
    ArrayList<BallVo> ballVos = new ArrayList<>();
    for (SysBall ball : list) {
        BallVo  ballVo= new BallVo();
        BeanUtils.copyProperties(ball, ballVo);
        SysXmglFile sysXmglFile = new SysXmglFile();
        sysXmglFile.setParId(ball.getId());
        sysXmglFile.setTableName("sys_ball");
        sysXmglFile.setSonId(0L);
        /*查询附件*/
        List<SysXmglFile> sysXmglFiles = sysXmglFileService.selectSysXmglFileList(sysXmglFile);
        ballVo.setSysXmglFiles(sysXmglFiles);
        ballVos.add(ballVo);
    }
    TableDataInfo dataTable = getDataTable(ballVos);
    dataTable.setTotal(new PageInfo(list).getTotal());
    return dataTable ;
}

=============

复制代码
@RequiresPermissions("system:ball:query")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
    SysBall ball = sysBallService.selectSysBallById(id);
    BallVo ballVo = new BallVo();
    BeanUtils.copyProperties(ball, ballVo);
    SysXmglFile sysXmglFile = new SysXmglFile();
    sysXmglFile.setParId(ball.getId());
    sysXmglFile.setTableName("sys_ball");
    sysXmglFile.setSonId(0L);
    /*查询附件*/
    List<SysXmglFile> sysXmglFiles = sysXmglFileService.selectSysXmglFileList(sysXmglFile);
    ballVo.setSysXmglFiles(sysXmglFiles);
    return success(ballVo);
}

===========================

新增输入

复制代码
/*任务附件上传*/
@PostMapping("/upload/file")
@Transactional(rollbackFor = Exception.class)
public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] files, @RequestParam("data") String data) {
    //这里的data是同时携带的其它信息就是前端的form里的信息,可以是用下面的json方式解析为自己相应的对象
    SysBall sysBall = JSONObject.toJavaObject(JSONObject.parseObject(data), SysBall.class);
    SysXmglFile sysXmglFile = new SysXmglFile();
    sysXmglFile.setParId(sysBall.getId());
    /*有子父级关系录入*/
    sysXmglFile.setSonId(0L);
    sysXmglFile.setTableName("sys_ball");
    return iSysXmglFileService.uploadFile(files,sysXmglFile);

}

=============

通过表单ID查询附件

复制代码
/*通过球阀表ID去查询附件名称单个*/
@GetMapping("/read/{id}")
@Transactional(rollbackFor = Exception.class)
public AjaxResult readTaskFile(@PathVariable("id") Long id) {
    SysXmglFile sysXmglFile = new SysXmglFile();
    sysXmglFile.setParId(id);
    /*有子父级关系录入*/
    sysXmglFile.setSonId(0L);
    sysXmglFile.setTableName("sys_ball");
    /*文件多个*/
    List<SysXmglFile> sysXmglFiles = iSysXmglFileService.readFile(sysXmglFile);

    List<BallFileVo> ballFileVos = new ArrayList<>();
    /*转换成地址和文件名称*/
    sysXmglFiles.forEach(sysXmglFile1 -> ballFileVos.add(new BallFileVo(sysXmglFile1)));

    return AjaxResult.success(ballFileVos);
}

=================

更新附件

复制代码
/*更新*/
@PostMapping("/upload/updateBallFile")
@Transactional(rollbackFor = Exception.class)
public AjaxResult deleteFile(@RequestBody List<String> filePath) {
    try {
        for (String deleteFilePath : filePath) {
            sysXmglFileService.deleteFilePath(deleteFilePath);
            FileUtils.deleteFile(deleteFilePath);
        }
        return AjaxResult.success("修改成功");
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return AjaxResult.error(e.getMessage());
    }
}

==========

下载附件

复制代码
@Log(title = "导出附件", businessType = BusinessType.EXPORT)
@PostMapping("/download/resource")
public void resourceDownload(String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    FileUtils.writeBytes(filePath, response.getOutputStream());
}
相关推荐
web14786210723几秒前
C# .Net Web 路由相关配置
前端·c#·.net
m0_748247801 分钟前
Flutter Intl包使用指南:实现国际化和本地化
前端·javascript·flutter
飞的肖4 分钟前
前端使用 Element Plus架构vue3.0实现图片拖拉拽,后等比压缩,上传到Spring Boot后端
前端·spring boot·架构
青灯文案112 分钟前
前端 HTTP 请求由 Nginx 反向代理和 API 网关到后端服务的流程
前端·nginx·http
m0_7482548817 分钟前
DataX3.0+DataX-Web部署分布式可视化ETL系统
前端·分布式·etl
ZJ_.28 分钟前
WPSJS:让 WPS 办公与 JavaScript 完美联动
开发语言·前端·javascript·vscode·ecmascript·wps
GIS开发特训营33 分钟前
Vue零基础教程|从前端框架到GIS开发系列课程(七)响应式系统介绍
前端·vue.js·前端框架·gis开发·webgis·三维gis
Cachel wood1 小时前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架
学代码的小前端1 小时前
0基础学前端-----CSS DAY9
前端·css
joan_851 小时前
layui表格templet图片渲染--模板字符串和字符串拼接
前端·javascript·layui