先说上传吧,lz写过多次上传方法,但是都是复制粘贴,这次重要有机会没在纯复制(也许是复制的不能用,哈哈);
废话不多说,直接上代码,以后对大家也有帮助;
html部分,使用的from标签
<div class="alert alert-info">
<form id="uploadForm" enctype="multipart/form-data" method="post">
<input type="file" id="templateFile" name="templateFile" style="display:none;" onchange="importFile()"/>
<a class='btn' href='javascript:void(0);' th:onclick="'javascript:uploadTemplate();'" >上传</a>
</form>
</div>
js部分
function uploadTemplate(){
document.getElementById("templateFile").click();
}
function importFile(){
if(!FileTypeCheck()) {
return false;
}
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
type: 'post',
url: "/****/****/****",
data: formData,
cache: false,
processData: false,
contentType: false,
}).success(function (data) {
var dataMap = JSON.parse(data);
if (0 !== dataMap.code) {
layer.msg(dataMap.errMsg, {icon: 1, shade: 0, time: 2000}, function () { location.reload();});
}else{
layer.msg(dataMap.errMsg, {icon: 2, shade: 0, time: 2000}, function () {});
}
}).error(function () {
layer.msg("上传失败", {icon: 2, shade: 0, time: 2000}, function () {});
});
}
function FileTypeCheck()
{
var obj =document.getElementById('templateFile');
if(obj.value==null || obj.value ==''){
layer.msg('请选择xml文件', {icon: 2, shade: 0, time: 2000}, function () {});
this.focus()
return false;
}
var length = obj.value.length;
var charindex = obj.value.lastIndexOf(".");
var ExtentName = obj.value.substring(charindex,charindex+4);
if(!(ExtentName == ".xml" )){
layer.msg('请上传xml文件', {icon: 2, shade: 0, time: 2000}, function () {});
this.focus()
return false;
}
return true;
}
后台接收部分
上传方法:
public static String upload(MultipartFile file,String path ) {
Map<String, String> rtnMap = new HashMap<String, String>();
rtnMap.put("code", "0");
if (!file.isEmpty()) {
//文件名
String saveFileName = file.getOriginalFilename();
File saveFile = new File(path + saveFileName);
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
out.write(file.getBytes());
out.flush();
out.close();
logger.info(saveFile.getName() + " 上传成功");
rtnMap.put("url",path + saveFileName);
rtnMap.put("fileName", saveFileName);
rtnMap.put("msgInfo", "上传成功");
rtnMap.put("code", "1");
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.info("上传失败," + e.getMessage());
rtnMap.put("msgInfo", "上传失败"+ e.getMessage());
} catch (IOException e) {
e.printStackTrace();
rtnMap.put("msgInfo", "上传失败"+ e.getMessage());
}
} else {
logger.info("上传失败,因为文件为空.");
rtnMap.put("msgInfo", "上传失败,因为文件为空.");
}
return JsonUtils.toJsonNoException(rtnMap);
}
如有问题还请各位留言告知。