java Springmvc ajax上传

时间:2023-03-10 04:16:52
java Springmvc ajax上传

ajax上传方式相对于普通的form上传方式要便捷,在更多的时候都会使用ajax (简单的小示例)

1.要先去下载一个 jquery.ajaxfileupload.js(基于jquery.js上的js) 还有jquery.js

2.首先要先配置一下servlet.xml

<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000" />
</bean>

3.在jsp页面上的form表单中

 <form action="shxt_upload03" method="post" >
文件上传:
<input type = "file" name="myFile" id="myFile" /> <br/>
<input type = "text" name= "shxt" id="shxt" />
<input type = "submit" value="上传文件" />
</form>

<script type="text/javascript">
    $(function(){
       $('#myFile').ajaxfileupload({
         'action': 'shxt_upload03',
         'onComplete': function(response) {
          },
         'onCancel': function() {
        }

});
   });
 </script>

4.在controller里面

public ModelAndView test01(MultipartFile myFile,HttpServletRequest request,HttpServletResponse response){

        //1.判断文件是否存在
if(!myFile.isEmpty()){
//2.获取服务器的绝对路径
String path = request.getSession().getServletContext().getRealPath("/upload");
//3.判断文件夹是否存在
File floder = new File(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;
}