【JavaWeb】ajax异步文件上传
原创
©著作权归作者所有:来自51CTO博客作者heituan的原创作品,请联系作者获取转载授权,否则将追究法律责任
1. html部分
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="file" name="file" />
<input type="button" value="上传" id="upload" />
</form>
2. js部分
$(document).ready(function(){
$("#upload").click(function(){
$.ajax({
url: 'upload.do',
type: 'POST',
cache: false,
data:new FormData($('#uploadForm')[0]),//h5的DataForm对象
dataType:"json",
processData: false,
contentType: false,
success:function(data){
alert(data.status);
}
})
})
})
3. java部分
@ResponseBody
@RequestMapping("upload.do")
public String upload(String un,@RequestParam("file") MultipartFile[] file, HttpServletRequest req)
throws IllegalStateException, IOException {
String basePath = "C:\\WebFile\\yao2san\\";
boolean isSuccess = false;
for (MultipartFile f : file) {
String path = "";
if (!f.isEmpty()) {
if (f.getOriginalFilename().endsWith("txt"))
path = basePath + "doc";
else if (f.getOriginalFilename().endsWith("jpg") || f.getOriginalFilename().endsWith("gif")
|| f.getOriginalFilename().endsWith("png"))
path = basePath + "img";
else
path = basePath + "other";
String fileName = f.getOriginalFilename();
File tarFile = new File(path, fileName);
f.transferTo(tarFile);
isSuccess = true;
}
}
return "{\"status\":"+isSuccess+"}";
}
网络上志同道合,我们一起学习网络安全,一起进步,QQ群:694839022