若依自定义文件上传下载

前端核心参数

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());
}
相关推荐
开心工作室_kaic1 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
刚刚好ā1 小时前
js作用域超全介绍--全局作用域、局部作用、块级作用域
前端·javascript·vue.js·vue
沉默璇年2 小时前
react中useMemo的使用场景
前端·react.js·前端框架
yqcoder2 小时前
reactflow 中 useNodesState 模块作用
开发语言·前端·javascript
2401_882727572 小时前
BY组态-低代码web可视化组件
前端·后端·物联网·低代码·数学建模·前端框架
SoaringHeart3 小时前
Flutter进阶:基于 MLKit 的 OCR 文字识别
前端·flutter
会发光的猪。3 小时前
css使用弹性盒,让每个子元素平均等分父元素的4/1大小
前端·javascript·vue.js
天下代码客3 小时前
【vue】vue中.sync修饰符如何使用--详细代码对比
前端·javascript·vue.js
猫爪笔记3 小时前
前端:HTML (学习笔记)【1】
前端·笔记·学习·html
前端李易安4 小时前
Webpack 热更新(HMR)详解:原理与实现
前端·webpack·node.js