共计 2367 个字符,预计需要花费 6 分钟才能阅读完成。
1. 前端代码 -HTML
<div class="second-second" v-show="firstflag">
<input type="file" ref="clearFile" @change="getFile($event)" class="add-file-right-input" accept=".txt,.docx,.doc,.pdf" style="margin-top: 20px">
<span style="display:block;margin-top: 20px"> 反对扩展名:.txt .doc .docx .pdf </span>
<div class="file" v-html="loadxy"></div>
<div style="margin-top: 20px">
<input type="button" class="btn btn-primary" @click="submitAddFile" value="开始上传"/>
</div>
</div>
2. 前端代码 -JS
/* 抉择文件 */
getFile:function(event){
var file = event.target.files;
for(var i = 0;i<file.length;i++){
// 上传类型判断
var imgName = file[i].name;
var idx = imgName.lastIndexOf(".");
if (idx != -1){var ext = imgName.substr(idx+1).toUpperCase();
ext = ext.toLowerCase( );
if (ext!='pdf' && ext!='doc' && ext!='docx' && ext!='txt'){ }else{this.addArr.push(file[i]);
}
}else{}}
},
/* 开始上传 */
submitAddFile:function(){if(0 == this.addArr.length){layer.msg("请抉择文件", {icon: 1});
return;
}
var formData = new FormData();
for(var i=0;i<this.addArr.length;i++){formData.append('file',this.addArr[i]);
}
const vm = this
$.ajax({
type: "POST",
url: baseURL + "air/crackCalculateController/upload",
contentType:false,
processData:false,
data: formData,
success: function(r){if(r.code == 0){layer.msg("操作胜利", {icon: 1});
vm.loadxy = r.ret
}else{layer.alert(r.msg);
}
}
});
}
3. 后盾代码 -Controller
@PostMapping("/upload")
@RequiresPermissions("air:crackCalculate:save")
public R upload(@RequestParam("file") MultipartFile file) throws IOException {if (file.isEmpty()) {return R.ok().put("ret", "上传失败,请抉择文件");
}
String fileName = file.getOriginalFilename();
String lastStr = fileName.substring(fileName.lastIndexOf("."));
String result = "";
if (".txt".equals(lastStr)) {
//10,100,1000/n20,200,2000/n30,300,3000/n
result = FileToString.convertStreamToString(file.getInputStream());
} else if ("doc".equals(lastStr)){String prefix = fileName.substring(fileName.lastIndexOf("."));
File filef = null;
try {filef = File.createTempFile(fileName, prefix);
file.transferTo(filef);
result = FileToString.convertDocToString(filef);
} catch (Exception e) {e.printStackTrace();
} finally {
// 操作完下面的文件 须要删除在根目录下生成的临时文件
File f = new File(filef.toURI());
f.delete();}
} else if (".docx".equals(lastStr)){String prefix = fileName.substring(fileName.lastIndexOf("."));
File filef = null;
try {filef = File.createTempFile(fileName, prefix);
file.transferTo(filef);
result = FileToString.convertDocxToString(filef);
} catch (Exception e) {e.printStackTrace();
} finally {
// 操作完下面的文件 须要删除在根目录下生成的临时文件
File f = new File(filef.toURI());
f.delete();}
}
return R.ok().put("ret", result);
}
}
正文完