java(springboot)+elementui实现多文件上传到本地服务器
垃圾代码,自行理解
1 java
1.1 yml配置(properties同)
max-xxx-xxx设置文件最大接受值
# Spring
spring:
servlet:
multipart:
enabled: true
max-file-size: 200MB
max-request-size: 200MB
1.2 controller
MultipartFile为文件,其他表单信息以Json格式发送过来
@PostMapping("/addContract")
public AjaxResult addContract(@RequestParam("files") List<MultipartFile> files, @RequestParam("fileNames") List multipartFileNames,
@RequestParam("erpContract") Object obj ){
String contractId = erpContractService.insertErpContract(obj, files, multipartFileNames);
//返回插入合同的合同编号
return AjaxResult.success(contractId);
}
1.3 service
public String insertErpContract(Object obj,List<MultipartFile> files, List multipartFileNames);
1.4 serviceImpl
t跳到====>erpContractFileService.insertErpContractFile(erpContract,files,multipartFileNames);
/**
* 新增合同信息
*
* @param obj 合同信息
* @return contractId
*/
@Override
@Transactional(rollbackFor = Exception.class)
public String insertErpContract(Object obj,List<MultipartFile> files, List multipartFileNames) {
JSONObject jsonObject = JSONObject.parseObject(obj.toString());
ErpContract erpContract = BeanUtil.toBean(jsonObject, ErpContract.class);
//首次插入 生成合同号
String contractId = this.generateContractNumber(erpContract);
erpContract.setContractId(contractId);
erpContract.setCreateUser(SecurityUtils.getUsername());
erpContract.setCreateTime(DateUtils.getNowDate());
erpContract.setDeleteFlag(0L);
erpContractMapper.insertErpContract(erpContract);
//添加后返回合同编号id
//传入的是erpContract 而不是erpContractFile哈
erpContractFileService.insertErpContractFile(erpContract,files,multipartFileNames);
//发票信息和支付信息单独添加
return contractId;
}
@Service
public class ErpContractFileServiceImpl implements IErpContractFileService {
@Autowired
private ErpContractFileMapper erpContractFileMapper;
/** 省略 */
@Override
public void insertErpContractFile(ErpContract erpContract, List<MultipartFile> files, List multipartFileNames) {
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);//获取文件
Object fileName = multipartFileNames.get(i);//获取源文件名
String newFileName = fileName.toString();//把文件名类型转换为String类型
String contractName = erpContract.getContractName();
//处理并保存文件到本地 handleFileAndSave
//将文件存进硬盘中
String filePath = this.saveFile(file, newFileName, contractName);
//传入contractId,fileName,filePath传入ErpContractFile实体类
ErpContractFile erpContractFile = new ErpContractFile();
erpContractFile.setContractId(erpContract.getContractId());
erpContractFile.setFilePath(filePath);
erpContractFile.setUploadTime(DateUtils.getNowDate());
erpContractFile.setUploadUser(SecurityUtils.getUsername());
erpContractFile.setDeleteFlag(0);
erpContractFileMapper.insertErpContractFile(erpContractFile);
}
}
@Override
public String saveFile(MultipartFile file, String newFileName, String contractName) {
return MyFileUtils.uploadFile(file, newFileName, contractName);
}
}
1.5 流
保存文件到服务器硬盘
public class MyFileUtils {
/**省略*/
public static String uploadFile(MultipartFile file, String newFileName, String contractName) {
String pathName = "";
File dir = new File("D:\\erpContract\\"+contractName);
//文件夹不存在便创建文件夹,文件夹存在便不创建
if( !dir.exists()&&!dir.isDirectory() ) dir.mkdirs();
//传进来的参数没起作用,
pathName = dir+"\\" + newFileName;//将存储地址与文件名拼接在一起
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pathName);
fos.write(file.getBytes());//写入文件
return pathName;
} catch (Exception e) {
e.printStackTrace();
return pathName;
} finally {
try {
fos.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.6 mapper
保存文件路径到数据库
<insert id="insertErpContractFile" useGeneratedKeys = "true" keyProperty = "id" parameterType="com.xxx.erp.contract.domain.ErpContractFile">
insert into erp_contract_file
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="contractId != null and contractId != ''">contract_id,</if>
<if test="filePath != null and filePath!=''">file_path,</if>
<if test="uploadUser != null and uploadUser!=''">upload_user,</if>
<if test="uploadTime != null">upload_time,</if>
<if test="deleteFlag != null">delete_flag,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="contractId != null and contractId != ''">#{contractId},</if>
<if test="filePath != null and filePath!=''">#{filePath},</if>
<if test="uploadUser != null and uploadUser!=''">#{uploadUser},</if>
<if test="uploadTime != null">#{uploadTime},</if>
<if test="deleteFlag != null">#{deleteFlag},</if>
</trim>
</insert>
2 vue 前端
2.1 vue
<el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="150px" >
<!--省略-->
<el-col >
<el-upload
class="upload-demo"
action="http://xxxx/xxxx/xxxx/xxxxx"
ref="upload"
enctype="multipart/form-data"
:http-request="httpRequest"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-change="onChangeFile"
:before-remove="beforeRemove"
:on-exceed="handleExceed"
:auto-upload="false"
multiple
:file-list="fileList">
<el-form-item label="合同附件" >
<el-button type="primary" align="center">上传附件<i class="el-icon-upload el-icon--right"></i></el-button>
</el-form-item>
</el-upload>
</el-col>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitPay">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
2.2 js提交表单
submitForm(file) {
if(this.form.contractId){
this.$alert('不可在本合同下再新建合同,您可以添加新的支付信息或者发票信息', '提示', {
confirmButtonText: '确定',
callback: action => {
this.$message({
type: 'info',
message: `action: ${ action }`
});
}
})
}else{
let { uploadFiles } = this.$refs.upload
let param = new FormData()
// 在这里对每一张图片进行大小的校验,如果不符合则提示,所有不符合的都提示,校验完成后只要有不符合条件的就不执行下面的操作
uploadFiles.forEach(item => {
param.append("files", item.raw);
param.append("fileNames", item.name);
})
param.append("erpContract", JSON.stringify(this.form));
/** 上传的参数有fileName,file,projectsAddBo表单参数-添加项目的信息*/
addContract(param).then(response => {
//应该返回一个id,然后赋值给form.id
this.form.contractId = response.msg;
this.open = false;
this.$alert('新增成功', '提示', {
confirmButtonText: '确定',
callback: action => {
this.$message({
type: 'success',
message: `action: ${ action }`
});
}
});
this.getList();
this.$router.push({ path: '/xxxx/xxxx'});
})
}//else