后端代码:
1.实体类:
@Data
public class InspectionReport implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private long id;
/**
* 文件原始名称
*/
private String name;
/**
* 用户id
*/
private long userId;
/**
* 用户名
*/
private String username;
/**
* 创建人
*/
private long createUserId;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 修改人
*/
private long modifyUserId;
/**
* 修改时间
*/
private LocalDateTime modifyTime;
private Long fileSize;
/**
* 存储类型
*/
private String storeType;
/**
* 存储的路径
*/
private String storePath;
}
2.controller层:
@RestController
@RequestMapping("/inspectionReport")
public class InspectionReportController {
@Autowired
private InspectionReportService inspectionReportService;
@RequestMapping("/uploadFile")
public ResultData uploadFile(@RequestAttribute Long _userId, HttpServletRequest request) {
try {
request.setCharacterEncoding("utf-8");
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
String originalName = uploadFile.getOriginalFilename();
boolean flag = inspectionReportService.getFileByFileName(originalName);
if (flag != true) {
InspectionReport inspectionReport = inspectionReportService.saveUploadFile(_userId, request);
return ResultData.success("ok", inspectionReport);
} else {
return ResultData.error("当前上传文件数据库已存在,您可以查询之后进行修改或者修改名称后再上传");
}
} catch (Exception e) {
e.printStackTrace();
return ResultData.error("error");
}
}
}
3.service层
public interface InspectionReportService extends IService<InspectionReport> {
boolean getFileByFileName(String originalName);
InspectionReport saveUploadFile(Long _userId, HttpServletRequest request);
}
4.serviceimpl层
@Service
public class InspectionReportServiceImpl extends ServiceImpl<InspectionReportMapper, InspectionReport> implements InspectionReportService {
@Value("${file.upload.path}")
private String uploadPath;
@Value("${file.upload.mapping}")
private String showPath;
@Autowired
private InspectionReportMapper inspectionReportMapper;
public boolean getFileByFileName(String originalName) {
QueryWrapper<InspectionReport> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", originalName);
List<InspectionReport> list = inspectionReportMapper.selectList(queryWrapper);
if (list.size() > 0) {
return true;
} else {
return false;
}
}
@Override
public InspectionReport saveUploadFile(Long _userId, HttpServletRequest request) {
try {
String abstractPath1 = null, relativePath1 = null;
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
String originalName = uploadFile.getOriginalFilename();
String file_ext_name = originalName.substring(originalName.lastIndexOf(".") + 1);
abstractPath1 = uploadPath + "static" + File.separator + "file" + File.separator + "yulan";
relativePath1 = showPath + "static" + "/" + "file" + "/" + "yulan";
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + file_ext_name;
File dir = new File(abstractPath1);
if (!dir.exists()) {
dir.mkdirs();
}
String relativePath = relativePath1 + "/" + originalName;
String abstractPath = abstractPath1 + File.separator + originalName;
FileCopyUtils.copy(uploadFile.getInputStream(), new FileOutputStream(abstractPath));
InspectionReport inspectionReport = saveData(_userId, originalName, relativePath, file_ext_name,
uploadFile.getSize(), abstractPath, fileName);
return inspectionReport;
} catch (Exception e) {
log.error("file_upload", e);
throw new UploadFileException("上传文件失败");
}
}
private InspectionReport saveData(Long userId, String originalName, String relativePath, String fileExtName, long size, String abstractPath, String fileName) {
InspectionReport inspectionReport = new InspectionReport();
inspectionReport.setId(SnowflakeIdGenerator.getId());
inspectionReport.setName(fileName);
inspectionReport.setUserId(userId);
inspectionReport.setFileSize(size);
inspectionReport.setStorePath(abstractPath);
inspectionReportMapper.insert(inspectionReport);
return inspectionReport;
}
}
前端代码:
<template>
<div style="width:100%;height:auto; margin:0 auto;">
<el-form :model="form" label-width="100px" label-position="left">
<el-row :gutter="20">
<el-col :span="24">
<el-form-item>
<div slot="label">项目名称<font color="red">*</font></div>
<el-select v-model="form.dirId" clearable style="width:100%;" @change="selectGoodsByGroupId($event)">
<el-option v-for="item in symbols" :key="item.id" :label="item.name" :value="item.id" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item>
<div slot="label">运维标题<font color="red">*</font></div>
<el-input v-model="form.title" placeholder="运维标题" />
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="8">
<el-form-item>
<div slot="label">运维人员<font color="red">*</font></div>
<!-- <el-input v-model="form.staffId" placeholder="运维人员" /> -->
<el-select v-model="form.staffId" clearable style="width:100%;" @change="selectGoodsByGroupId($event)">
<el-option v-for="item in symbols2" :key="item.id" :label="item.nickName" :value="item.id" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="16">
<el-form-item>
<div slot="label">运维日期<font color="red">*</font></div>
<el-date-picker
v-model="form.itemTime"
value-format="yyyy-MM-dd"
class="filter-item"
type="daterange"
range-separator="至"
start-placeholder="运维开始日期"
end-placeholder="运维结束日期"
style="width: 100%;"
:clearable="false"
/>
</el-form-item>
</el-col>
</el-row>
<el-form-item label="内容">
<el-input v-model="form.content" type="textarea" :autosize="{ minRows: 3, maxRows: 6}" />
</el-form-item>
<el-form-item label="备注">
<el-input v-model="form.message" type="textarea" :autosize="{ minRows: 3, maxRows: 6}" />
</el-form-item>
<el-form-item label="检测报告" prop="gysId">
<el-upload
class="upload-demo"
accept=".jpg,.png,.jpeg,.bmp,.gif,.svg,.mp4,.avi,.wmv,.mpg,.rmvb,.flv,.doc,.docx,.xlsx"
:on-change="handleChange"
:action="uploadpath"
:headers="uoloadheaders"
:on-success="handleAvatarSuccess"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:file-list="fileList"
:before-upload="beforeAvatarUpload"
name="uploadfile_ant"
>
<el-button size="small" icon="el-icon-upload" type="primary">选择文件</el-button>
<span style="color:red;"> 上传文件不超过100m</span>
</el-upload>
</el-form-item>
</el-form>
<div style="text-align:center;">
<el-button type="primary" @click="save()">保存</el-button>
<el-button type="danger" @click="closePage">取消</el-button>
</div>
</div>
</template>
<script>
import { saveData } from '@/api/operationMaintenance'
import { getAllList } from '@/api/maApplicationInfo'
import { Message } from 'element-ui'
import {getUserList,getId} from '@/api/user'
import tool from '@/utils/tool'
export default {
inject: ['getList'],
data() {
return {
form: {},
uploadpath: '',
types: [],
batchCode:'',
symbols: [],
symbols2:[],
uoloadheaders: {},
fileData: '', // 文件上传数据(多文件合一)
fileList: [] // upload多文件数组
}
},
created() {
this.getproject()
},
methods: {
getproject(){
getAllList().then(response=> {
this.symbols = response.data
})
getUserList().then(response=>{
this.symbols2 = response.data
})
this.batchCode = ''
getId().then(res => {
this.batchCode = res.data
let address = process.env.NODE_ENV == 'development' ? process.env.VUE_APP_URL_RECON : process.env.VUE_APP_BASE_API;
var path = '/inspectionReport/uploadFile'
this.uploadpath = address + path
console.log(this.uploadpath)
this.uoloadheaders = {
'X-TOKEN' : tool.getCookie('X-Token'),
'client-url':location.href,
'applicationId':this.applicationId
}
})
},
selectGoodsByGroupId(val) { // 根据设备组id获取相应的商品
if (val != null && val !== '' && val !== undefined) {
for (var i = 0; i < this.symbols.length; i++) {
if (this.symbols[i].id === val) {
this.form.userId = this.symbols[i].customerMid
}
}
}
},
save(){
this.form.startTime = this.form.itemTime[0]
this.form.endTime = this.form.itemTime[1]
const loading = this.$loading({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
saveData(this.form).then(response => {
Message({
message: '新增成功',
type: 'success',
duration: 5 * 1000
})
this.$emit('update:visible', false)
loading.close()
this.getList()
}).catch(response => {
loading.close()
this.getList()
})
},
handleChange(file, fileList) {
let fileName = file.name;
let uid = file.uid
let pos = fileName.lastIndexOf(".");
let lastName = fileName.substring(pos, fileName.length);
var suffix = '.jpg,.png,.jpeg,.bmp,.gif,.svg,.mp4,.avi,.wmv,.mpg,.rmvb,.flv,.doc,.docx,.xlsx'
if (suffix.indexOf(lastName.toLowerCase()) === -1) {
this.$message.error("文件必须为.jpg,.png,.jpeg,.bmp,.gif,.svg,.mp4,.avi,.wmv,.mpg,.rmvb,.flv,.doc,.docx,.xlsx类型");
for(var i = 0;i<fileList.length;i++) {
if(fileList[i].uid == uid) {
fileList.splice(i,1)
}
}
return;
}
const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
if (existFile) {
this.$message.error('当前文件已经存在!')
fileList.pop()
}
this.fileList = fileList
},
handleAvatarSuccess(res, file) {
this.uploadLoading = false
if (res.code === 20000) {
// this.form = res.data
this.upVisible = false
Message({
message: '上传成功',
type: 'success',
duration: 5 * 1000
})
} else {
this.upVisible = true
Message({
message: res.msg,
type: 'error',
duration: 5 * 1000
})
}
},
handleRemove(file, fileList) {
this.fileList = fileList
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
},
beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 100
if (!isLt2M) {
this.$message.error('上传文件大小不能超过100MB!')
}
return isLt2M
},
closePage() {
this.$emit('update:visible', false)
},
}
}
</script>