若依自定义文件上传下载

前端核心参数

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());
}
相关推荐
魏大帅。2 分钟前
Axios 的 responseType 属性详解及 Blob 与 ArrayBuffer 解析
前端·javascript·ajax
花花鱼8 分钟前
vue3 基于element-plus进行的一个可拖动改变导航与内容区域大小的简单方法
前端·javascript·elementui
k093312 分钟前
sourceTree回滚版本到某次提交
开发语言·前端·javascript
EricWang135833 分钟前
[OS] 项目三-2-proc.c: exit(int status)
服务器·c语言·前端
September_ning33 分钟前
React.lazy() 懒加载
前端·react.js·前端框架
web行路人43 分钟前
React中类组件和函数组件的理解和区别
前端·javascript·react.js·前端框架
番茄小酱00144 分钟前
Expo|ReactNative 中实现扫描二维码功能
javascript·react native·react.js
子非鱼9211 小时前
【Ajax】跨域
javascript·ajax·cors·jsonp
超雄代码狂1 小时前
ajax关于axios库的运用小案例
前端·javascript·ajax
长弓三石1 小时前
鸿蒙网络编程系列44-仓颉版HttpRequest上传文件示例
前端·网络·华为·harmonyos·鸿蒙