zoukankan      html  css  js  c++  java
  • 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; }
  • 相关阅读:
    常见WINDOWS运行命令
    CSDN Blog 之七宗罪
    常见进程大全
    开始→运行→输入的命令集锦(网上搜来的)
    20200527:SpringCloud用了那些组件?分布式追踪链怎么做的?熔断器工作原理?
    20200520:分库分表后如何迁移?
    20200523:如何实现并发限流
    20200521:es底层读写原理?倒排索引原理?
    20200525:MQ应用场景、Kafka和rabbit区别?kafka为什么支撑高并发? 来自
    20200519:催收核心业务是什么?
  • 原文地址:https://www.cnblogs.com/xkl520xka/p/5413001.html
Copyright © 2011-2022 走看看