因为表格中有文件类型的上传与下载,在上传请求中需要给到记录Id,在此记录一下正确方式。
效果图:
一、前端发送请求
<!--文件操作-->
<el-table-column align="center" v-if="fileActionShow" :fixed="addBtnList.fixed" :label="fileAction.name" :min-width="fileAction.width">
<template slot-scope="scope">
<el-button @click="clickCall('handleImport', scope)">
<el-upload class="upload-demo" :action="fileAction.fileUploadUrl" :show-file-list="false" :limit="1" :multiple="false" :auto-upload="true" accept=".xml" :before-upload="beforeUpload"
:headers="fileAction.uploadHeaders" :data="fileAction.uploadData">上传
</el-upload></el-button>
<el-button @click="clickCall('handleExport', scope)"> <a :href="fileAction.fileUploadUrl">导出</a></el-button>
</template>
</el-table-column>
import Cookie from "js-cookie";
data:
fileAction: {
width: 60,
name: "XML文件",
fileUploadUrl: "/*****/importXml",
fileExportUrl: "/*****/exportXml",
uploadData: {},
uploadHeaders: {},
},
method:
// 文件上传操作
handleImport(row) {
this.fileAction.uploadData = {
id: row.id,
};
// Token一定要加,否则报401,因为这是自己写的请求,不是封装的,不会自带token
this.fileAction.uploadHeaders = {
Authorization: Cookie.get("droneToken"),
};
},
//上传之前
beforeUpload(file, fileList) {
let promise = new Promise((resolve) => {
this.$nextTick(function () {
resolve(true);
});
});
return promise;
},
二、后端代码实现
Controller层
@ApiOperation("导入数据")
@PostMapping("importXml")
public Result importData(@RequestParam(value="file") MultipartFile file, @RequestParam(value="id") Long id) throws Exception {
return routeService.importData(file, id);
}
当然,如果存储文件到数据库Blog类型,笔者采用PreparedStatement存储
@Override
public Result importData(MultipartFile file, Long id) throws SQLException {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = new JDBCConnection().getConnection();
String sql = "update xxx set file_txt=? where id=?";
ps = connection.prepareStatement(sql);
InputStream inputStream = file.getInputStream();
ps.setBlob(1,inputStream);
ps.setLong(2,id);
ps.execute();
} catch (IOException e) {
e.printStackTrace();
}finally {
connection.close();
ps.close();
}
return Result.success("上传成功");
}
JDBCConnection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConnection {
private static final String DBDRIVER="com.mysql.cj.jdbc.Driver";
private static final String DBURL = "填自己的地址";
public static final String USERNAME="填自己的账号";
public static final String PASSWORD = "填自己的密码";
private Connection conn;
public JDBCConnection() {
//加载驱动
try {
Class.forName(DBDRIVER);
//获取连接
conn = DriverManager.getConnection(DBURL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
if(conn==null||conn.isClosed()){
conn = DriverManager.getConnection(DBURL, USERNAME, PASSWORD);
}
return this.conn;
}
public void close(){
if(this.conn!=null){
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
效果图:
存储成功,大兴西北。