前端html代码
<div class="p-upload-box">
<form action='dic/uploadWord' enctype='multipart/form-data' method='post' id="fileUpload">
<el-upload class="upload-demo" action="dic/uploadWord" id="file" name='file' ref="upload" :auto-upload='false'
:on-change='changeUpload' accept=".txt">
<a href="#" class="btn-line">
<svg class="icon" aria-hidden="true">
<use xlink:href="#icon-upload"></use>
</svg>
<span>上传文件</span>
</a>
<span class="cg9">支持txt格式文件</span>
</el-upload>
</form>
</div>
<div slot="footer" class="dialog-footer">
<el-button @click="insertContent" class="btn-line cur">确 定</el-button>
<el-button @click="centerDialogVisible = false" class="btn-line">取 消</el-button>
</div>
js代码
function insertContent(){
var form = document.getElementById("fileUpload");
var postData = new FormData(form);
$.ajax({
data : postData,
type : "POST",
url : url,
contentType: false,
processData: false,
success : function(result) {
if (result.code == 200) {
app.$message({
message:result.msg,
type: 'success'
});
}else{
app.$message.error({
message:result.msg,
type: 'fail'
});
}
}
});
this.centerDialogVisible = false;
//上传完成后清空文件
this.$refs.upload.clearFiles();
}
后台控制层代码
/**
* 批量新增词条(上传txt文件)
* @param request
* @return
*/
@ResponseBody
@PostMapping(value = "/uploadWord")
public BaseResponse<WordItem> uploadWord(HttpServletRequest request){
BaseResponse<WordItem> result = new BaseResponse<WordItem>();
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartHttpServletRequest.getFile("file");
int rowNumber = 0;
try {
byte[] content = file.getBytes();
String filePath = getFilePath(file);
FileOutputStream outputStream = new FileOutputStream(filePath);
outputStream.write(content);
outputStream.close();
String encoding="UTF-8";
File file2=new File(filePath);
if(file2.isFile() && file2.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file2),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
rowNumber++;
}
System.out.println(rowNumber);
read.close();
}else{
log.info("找不到指定的文件");
}
result.code = 200;
result.setMsg("导入完成,共导入"+rowNumber+"个词条!");
} catch (Exception e) {
e.printStackTrace();
result.code = 500;
result.setMsg("导入失败,服务器错误!");
}
return result;
}
private String getFilePath(MultipartFile file) {
String guid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
String fileName = file.getOriginalFilename();
String extName = fileName.substring(fileName.lastIndexOf("."));
String fileNameWithoutExt = fileName.replaceAll(extName, "");
String fileNewName = fileNameWithoutExt + "-" + guid + extName;
String filePath = fileUploadConfig.getSavePath() + fileNewName;
System.out.println("filePath" + filePath);
return filePath;
}