ajax上传方式相对于普通的form上传方式要便捷,在更多的时候都会使用ajax (简单的小示例)
1.要先去下载一个 jquery.ajaxfileupload.js(基于jquery.js上的js) 还有jquery.js
2.首先要先配置一下servlet.xml
3.在jsp页面上的form表单中
文件上传:$(function(){
$('#myFile').ajaxfileupload({
'action': 'shxt_upload03',
'onComplete': function(response) {
},
'onCancel': function() {
}
});
});
4.在controller里面
publicModelAndView test01(MultipartFile myFile,HttpServletRequest request,HttpServletResponse response){//1.判断文件是否存在
if(!myFile.isEmpty()){//2.获取服务器的绝对路径
String path = request.getSession().getServletContext().getRealPath("/upload");//3.判断文件夹是否存在
File floder = newFile(path);if(!floder.isDirectory()){//判断是否为文件夹,前提是文件存在
floder.mkdirs();//创建文件
}try{//4.获取上传文件的后缀名
String extension =FilenameUtils.getExtension(myFile.getOriginalFilename());//5.创建上传文件的新名称
//另外一种起名字的方式//String newName= UUID.randomUUID().toString()+"."+extension;
String newName = (new Date()).getTime()+"_"+(new Random().nextInt(10000))+"."+extension;
File newFile= new File(path+"/"+newName);
myFile.transferTo(newFile);//返回值
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
out.write(newName);
out.flush();
out.close();
}catch(Exception e) {//TODO: handle exception
}
}return null;
}