哲学分享:
人生在世,
不可不满自己,这是怯弱,源自不爱学习;
也不可自满,这是愚蠢,源自无知;
龙文浩: 读者您好,该文章我验证了无数次,代码非常可靠,如使用中有问题,可随时给我留言,欢迎反馈,谢谢阅读
VUE-template层:
<div class="demo-form-inline pagesBtn">
<el-upload class="upload-demo" ref="lwh-upload" :action="Elenemt_File_Url + '?token=' + this.$store.state.token + '&random=' + new Date().getTime()" :limit="1"
:on-change="Elenemt_OnChangeFile" :data="Elenemt_Data" :on-exceed="Elenemt_OnExceed"
:on-success="Elenemt_OnSuccess" :on-error="Elenemt_OnError" :before-upload="Elenemt_BeforeUpload"
:auto-upload="true">
<el-button slot="trigger" size="mini" type="danger" icon="el-icon-upload2" :disabled="Elenemt_Info.disabled">上传文件</el-button>
</el-upload>
<div slot="tip" class="el-upload__tip">温馨提示: 您好!请上传相关文件,谢谢您的配合! </div>
</div>
Vue-script层:
data(){
return {
//Elenemt上传文件---xxurl
Elenemt_File_Url:this.$ajaxUrl+this.$store.state.vtPart+"spartPartLSupplierService/SetxxLongWenhService.do",
//Elenemt上传文件---上传文件时附带的其他参数
Elenemt_Data:{
// 参数1:"值1",
},
//Elenemt上传文件---xx其他参数
Elenemt_Info:{
test:"",
label:"附件:",
accept:".xlsx, .xls, .doc, .docx, .jpg, .png, .jpeg, .pdf",
//用于在同个页面,多个上传组件调用时,知道在调用哪个
fileType:"",
//用于禁用按钮
disabled:false,
//el-col span的width
spanWidth:18,
//el-form-item label的width
labelWidth:"140px",
//上传时file的主键名
name:"file"
},
}
}
vue Method层
methods:{
//Elenemt上传文件---上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
Elenemt_BeforeUpload(file){
this.Notification({ title: '', message: '您好,发送上传请求中,请耐心等待!', type: 'info',duration:'0' });
},
//Elenemt上传文件---文件上传失败时的钩子
Elenemt_OnError(err, file, fileList){
this.Notification.closeAll();
this.Notification.error({ title: '', message: res.msg,duration:'3000' });
},
//Elenemt上传文件---文件上传成功时的钩子
Elenemt_OnSuccess(res, file, fileList){
this.$refs['lwh-upload'].clearFiles();
if (res.result == '1') {
this.Notification.closeAll();
this.$message({ message: res.msg, type: 'success',duration:'3000',showClose:true});
//this.getListContent(1);
} else if(res.result == '0') {
this.Notification.closeAll();
this.Notification({ title: '', message: res.msg, type: 'warning',duration:'3000' });
}else{
this.Notification.closeAll();
this.Notification.error({ title: '', message: res.msg,duration:'3000' });
}
},
//Elenemt上传文件---文件超出个数限制时的钩子
Elenemt_OnExceed(files, fileList){
this.Notification({ title: '', message: `当前限制选择 1 个文件,本次选择了 ${files.length ? files.length : 0} 个文件`, type: 'warning',duration:'3000' });
},
//Elenemt上传文件---:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用/
Elenemt_OnChangeFile(file,fileList){
if(fileList.length>1)fileList.shift(); //从前面删除一个数
},
}
java-Service层:
/**
* 上传附件到FTP 龙文浩/2022年1月18日
*/
private static java.lang.String ftp_ip="",ftp_userName="",ftp_pass="",enterLocalPassiveMode="";//IP,端口,用户,密码,是否被动
private static org.apache.commons.net.ftp.FTPClient ftp = null;//ftp
private static int ftp_host = 0;//ftp端口
@io.swagger.annotations.ApiOperation(value="上传附件到FTP",response = com.ly.mp.vt.common.response.Result.class,notes="上传附件到FTP")
@io.swagger.annotations.ApiParam(required=true,name="params",value="上传附件到FTP")
@org.springframework.web.bind.annotation.PostMapping(value="/SetxxLongWenhService.do")
public com.ly.mp.vt.common.response.Result SetxxLongWenhService(@org.springframework.web.bind.annotation.RequestBody org.springframework.web.multipart.MultipartFile file,java.lang.String sparePartId_S,java.lang.String sparePartFileType){
com.ly.mp.vt.common.response.Result result = new com.ly.mp.vt.common.response.Result();
result.setResult("-1");
try {
com.ly.mp.component.entities.UserEntity userEntity = super.getUser();
java.lang.String creator = userEntity.getUserName();//用户名
//验证,文件不能为空
if(file == null) {
result.setMsg("您好,file(文件),不能为空.");
return result;
}else if(sparePartId_S == null || sparePartId_S.equals("")) {
result.setResult("0");
result.setMsg("参数 xx_S(xxID,多个时使用英文逗号拼接),不能为空.");
return result;
}else if(sparePartFileType == null || sparePartFileType.equals("")) {
result.setResult("0");
result.setMsg("参数 xxType(文件类型),不能为空。【xx】 ");
return result;
}
java.lang.String str_file_name = file.getOriginalFilename();//*文件名
java.lang.String str_file_suff = "";//*文件后缀
java.lang.Integer int_index = str_file_name.lastIndexOf(".");
if(int_index != -1) {
str_file_suff = str_file_name.substring(int_index + 1);
str_file_suff = str_file_suff.toLowerCase();
}
if(!str_file_suff.equals("xlsx") && !str_file_suff.equals("xls") && !str_file_suff.equals("txt") && !str_file_suff.equals("pdf")
&& !str_file_suff.equals("doc") && !str_file_suff.equals("doc") && !str_file_suff.equals("jpg") && !str_file_suff.equals("png")) {
result.setMsg("您好!仅支持上传以下文件类型:.xlsx/.xls/.txt/.pdf/.doc/.docx/.jpg/.png");
return result;
}
//查,数据字典中FTP配置 龙文浩/2022年1月18日
java.lang.String dataDictionaryType = "FTP",dataDictionaryCode="",dataDictionaryVaule="";//类型,数据英文描述,数据值
java.util.List<com.ly.mp.vt.part.vo.PcSpareDataDictionaryVo> PcSpareDataDictionary = this.iSpartPartLSupplierBIZ.GetPcSpareDataDictionaryVo(dataDictionaryType);
if(PcSpareDataDictionary != null) {
for(com.ly.mp.vt.part.vo.PcSpareDataDictionaryVo pvo : PcSpareDataDictionary) {
dataDictionaryCode = pvo.getDataDictionaryCode();
dataDictionaryVaule = pvo.getDataDictionaryVaule();
dataDictionaryVaule = dataDictionaryVaule == null ? "" : dataDictionaryVaule.trim();
if(dataDictionaryCode.equals("FTP_IP")) { ftp_ip = dataDictionaryVaule; }
else if(dataDictionaryCode.equals("FTP_HOST")) { ftp_host =new java.lang.Integer(dataDictionaryVaule); }
else if(dataDictionaryCode.equals("FTP_UserName")) { ftp_userName = dataDictionaryVaule; }
else if(dataDictionaryCode.equals("FTP_Password")) { ftp_pass = dataDictionaryVaule; }
else if(dataDictionaryCode.equals("FTP_Passive")) { enterLocalPassiveMode = dataDictionaryVaule; }
}
}
java.io.InputStream in = file.getInputStream();//文件流
java.lang.String str_fileDir = "LSPFile/xx/xxFile";//FTP文件夹
java.lang.String fcdString = ftpCreateDirectory(str_fileDir,true);//指定ftp,创建存放合同的文件目录
if(fcdString == "success") {}
else {
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("setSendDoaAdditional", "失败!新建文件夹","新建文件夹失败,目录【"+str_fileDir+"】,原因:【"+fcdString+"】");
}
java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ssS");
java.util.Date dateNow = new java.util.Date();
java.lang.String str_date = simpleDateFormat.format(dateNow);
java.lang.String str_saveFileName = str_date + "." + str_file_suff;//保存文件名
java.lang.String str_saveFileAttr = str_fileDir + "/" + str_saveFileName;//保存文件路径
ftp = getFTPClient(ftp_ip,ftp_host,ftp_userName,ftp_pass);//连接ftp服务器
if(enterLocalPassiveMode.equals("1")) {
ftp.setControlEncoding("UTF-8");
ftp.enterLocalPassiveMode();
}
java.lang.Boolean boolStoreFile = ftp.storeFile(str_saveFileAttr,in);
in.close();
if(boolStoreFile) {
java.lang.String[] str_sparePartId = sparePartId_S.split(",");
java.lang.Integer int_total = str_sparePartId.length;
java.lang.Integer int_success = 0;
for(java.lang.String sparePartId : str_sparePartId) {
//增,xx文件表 龙文浩/2022年1月18日
dateNow = new java.util.Date();
java.lang.String xx_file_id = simpleDateFormat.format(dateNow);//文件ID
java.lang.String xx_file_link_id = sparePartId;//外键ID
java.lang.String xx_file_type = sparePartFileType;//'文件类型
java.lang.String xx_file_name = str_file_name;//文件名(取用户端的文件名)
java.lang.String xx_file_address = str_saveFileAttr;//文件路径;LSPFile/Spare/SupplierFile/xx.xx
@SuppressWarnings("serial")
java.util.Map<java.lang.String,java.lang.String> hashMap = new java.util.HashMap<java.lang.String,java.lang.String>(){
{
put("xx_file_id",xx_file_id);
put("xx_file_link_id",xx_file_link_id);
put("xx_file_type",xx_file_type);
put("xx_file_name",xx_file_name);
put("xx_file_address",xx_file_address);
put("creator",creator);
}
};
java.lang.Integer int_InserFile = this.iSpartPartLSupplierBIZ.SetInsertSparePartFileService(hashMap);
if(int_InserFile < 0) {
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxLongWenhService", "上传附件到FTP出现异常",xx_file_link_id);
}else {
int_success = int_success + 1;
}
}
if(int_total == int_success) {
result.setResult("1");
result.setMsg("您好!文件上传成功!");
}else {
result.setResult("0");
result.setMsg("您好!共" + int_total + "行。成功" + int_success + "行,失败"+(int_total - int_success) + "行。详情查看日志表(select * from pc.t_pc_xx_log where xx_log_code = 'SetxxLongWenhService' order by created_date desc)");
}
}else {
result.setResult("1");
result.setMsg("您好!文件上传失败,请重试!");
}
}catch(Exception ex) {
result.setResult("-1");
result.setMsg(ex.getMessage());
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxLongWenhService", "上传附件到FTP",ex.toString());
}
return result;
}
/**
* 指定ftp,创建存放合同的文件目录 longwenh 2021/10/07
* @param create_path 创建文件目录
* @param create_bool 创建完成后退出登录,true退出,false不退出
* @return
*/
public java.lang.String ftpCreateDirectory(java.lang.String create_path,java.lang.Boolean create_bool) {
try {
ftp = getFTPClient(ftp_ip,ftp_host,ftp_userName,ftp_pass);//连接ftp服务器
if (ftp != null) {
if (!ftp.changeWorkingDirectory(create_path)) {
java.lang.String[] pageStrings = create_path.split("/");
java.lang.String pathString = "";
for (java.lang.String str : pageStrings) {
pathString = pathString + "/" + str;
if (!ftp.changeWorkingDirectory(pathString)) {
ftp.makeDirectory(pathString);
}
}
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxLongWenhService", "FTP文件夹创建成功",create_path);
}
}
else {
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxLongWenhService", "失败!ftp连接失败","请检查配置和权限:ftp_host【" + ftp_host +"】ftp_ip【"
+ftp_ip+ "】ftp_userName【" +ftp_userName + "】ftp_pass【"+ftp_pass+"】");
return "ftp连接失败,请检查配置和权限";
}
if(create_bool) {
ftp.disconnect();
}
} catch (Exception ex) {
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxLongWenhService", "失败!FTP文件夹创建",ex.toString());
return "ftp连接失败,请检查配置和权限" + ex.toString();
}
return "success";
}
/**
* 连接ftp服务器 龙文浩2022/01/18
* 获取FTPClient对象
* @param ftpHost FTP主机服务器
* @param ftpPassword FTP 登录密码
* @param ftpUserName FTP登录用户名
* @param ftpPort FTP端口 默认为21
* @return
*/
@java.lang.SuppressWarnings("static-access")
public org.apache.commons.net.ftp.FTPClient getFTPClient(java.lang.String ftpHost, java.lang.Integer ftpPort, java.lang.String ftpUserName, java.lang.String ftpPassword) {
org.apache.commons.net.ftp.FTPClient ftpClient = null;
try {
//创建ftp客户端
ftpClient = new org.apache.commons.net.ftp.FTPClient();
// 连接FTP服务器
ftpClient.connect(ftpHost, ftpPort);
// 登陆FTP服务器
ftpClient.login(ftpUserName, ftpPassword);
//设定文件流为2进制
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
if (!org.apache.commons.net.ftp.FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.disconnect();
} else {
System.out.println("FTP连接成功。");
}
} catch (java.net.SocketException e) {
ftpClient = null;
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxongWenhService", "失败!FTP连接异常","异常!连接ftp服务器:【" + e.toString()+"】");
} catch (java.io.IOException e) {
ftpClient = null;
//增加日志,【日志名称-关联单据号-错误日志描述-错误日志详情】
this.SetInsertLogFun("SetxxLongWenhService", "失败!FTP连接异常","异常!连接ftp服务器:【" + e.toString()+"】");
}
return ftpClient;
}