知识点: 1、选中文件后自动上传,没有多余的操作。 2、将文件上传到后台进行解析,读取文件内容,然后入库,不需要存储到某个路径下。当然了,代码里已早有准备,String path = tomcat +"/"+ fileName;
一、表单提交
1、前台 样式/js方法 限定选择TXT文本并自动上传
<form id="fileForm" name="fileForm" action="" method="post" enctype="multipart/form-data">
<!-- <a href="#" class="w_borblue"><input type="file">选择文件并上传</a> -->
<a href="#" class="a-upload a_btn_style"><input type="file" name="file" accept="text/plain" onchange ="uploadFile();"/>选择文件并上传</a>
</form>
function uploadFile(){
var id = $("#infoid").val();
$("#fileForm").attr("action", "/admin/cqcvc/upload?id="+id);
$('#fileForm').submit();
}
2、后台 方法 将上传的txt文本内容读取出来入库,不需要在本地存在xxx.txt文件
@Deprecated
@Get("upload")
@Post("upload")
public String upload(HttpServletRequest request, HttpServletResponse response, @Param("id") int id, MultipartFile file) throws Exception {
StringBuffer stringBuffer = new StringBuffer();
Reader reader = new InputStreamReader(file.getInputStream(), "utf-8");
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
stringBuffer.append(line + "\n");
System.out.println(line);
}
reader.close();
logger.info("txt文本内容:" + stringBuffer.toString());
courseinfoService.modify(stringBuffer.toString(), id);
return "r:/admin/cqcvc/list";
}
一、AJAX提交
1、accept:过滤需要上传的文件类型
<form id="fileForm" name="fileForm" action="" method="post" enctype="multipart/form-data">
<div class="pop_bnt">
<a class="a-upload a_btn_style" href="#"><input type="file" id="file" name="file" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" onchange ="importExcel();"/>批量导入</a>
</div>
</form>
2、这上导入EXCEL文件,上传其它类型文件的原理相通
function importExcel() {
var yshdhyid = $("#yshdhyid").val();
var formData = new FormData();
var name = $("#file").val();
formData.append("file",$("#file")[0].files[0]);
formData.append("name",name);
formData.append("yshdhyid",yshdhyid);
formData.append("role",1);
$.ajax({
url : '/ysphy/importExcel',
type : 'POST',
async : false,
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
alert(data);
window.location.reload();
}
});
}
注意:本文归作者所有,未经作者允许,不得转载