springMVC+jsp+ajax上傳文件


工作中遇到的小問題,做個筆記

實現springMVC + jsp + ajax 上傳文件

HTML

<body>
   <form id="myform"  method="post" >
       登錄名<input type="text" name="loginName" />
       <br>
      上傳錄音<input type="file" name="record" />
      <input type="button" onclick="doUpload()" value="提交" />
   </form> 
</body>

javascript

 function doUpload() {  
      var formData = new FormData($( "#myform" )[0]);  
      $.ajax({  
           url: 'insert/fileupload.action' ,  
           type: 'POST',  
           data: formData,  
           async: false,  
           cache: false,  
           contentType: false,  
           processData: false,  
           success: function (returndata) {  
               alert(returndata);  
           },  
           error: function (returndata) {  
               alert(returndata);  
           }  
      });  
 }

springMVC.xml

   <!-- 配置文件上傳解析器 -->  
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8"/>  
        <property name="maxUploadSize" value="10485760000"/>  
        <property name="maxInMemorySize" value="40960"/>  
     </bean> 

java

RequestMapping("fileupload")
 public void fileupload(HttpServletRequest request,HttpServletResponse response,String loginName) throws Exception {
     //獲取服務器中保存文件的路徑
  String path = request.getSession().getServletContext().getRealPath("")+"\\upload\\record\\";
  System.out.println(path);
   //獲取解析器  
     CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
     //判斷是否是文件  
     if(resolver.isMultipart(request)){  
         //進行轉換  
         MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);  
         //獲取所有文件名稱  
         Iterator<String> it = multiRequest.getFileNames();  
         while(it.hasNext()){  
             //根據文件名稱取文件  
             MultipartFile file = multiRequest.getFile(it.next());  
             String fileName = file.getOriginalFilename();  
             String localPath = path + fileName;  
             //創建一個新的文件對象,創建時需要一個參數,參數是文件所需要保存的位置
             File newFile = new File(localPath);  
             if (newFile.getParentFile() != null || !newFile.getParentFile().isDirectory()) {
                // 創建父文件夾
 newFile.getParentFile().mkdirs(); }
        //上傳的文件寫入到指定的文件中   
        file.transferTo(newFile);   
      }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM