若依自定义文件上传下载

前端核心参数

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());
}
相关推荐
桂月二二22 分钟前
探索前端开发中的 Web Vitals —— 提升用户体验的关键技术
前端·ux
CodeClimb1 小时前
【华为OD-E卷 - 第k个排列 100分(python、java、c++、js、c)】
java·javascript·c++·python·华为od
沈梦研1 小时前
【Vscode】Vscode不能执行vue脚本的原因及解决方法
ide·vue.js·vscode
hunter2062062 小时前
ubuntu向一个pc主机通过web发送数据,pc端通过工具直接查看收到的数据
linux·前端·ubuntu
qzhqbb2 小时前
web服务器 网站部署的架构
服务器·前端·架构
刻刻帝的海角2 小时前
CSS 颜色
前端·css
轻口味2 小时前
Vue.js 组件之间的通信模式
vue.js
浪浪山小白兔3 小时前
HTML5 新表单属性详解
前端·html·html5
lee5763 小时前
npm run dev 时直接打开Chrome浏览器
前端·chrome·npm
2401_897579653 小时前
AI赋能Flutter开发:ScriptEcho助你高效构建跨端应用
前端·人工智能·flutter